-1

I'm trying to implement a suffix tree.

int _tmain(int argc, _TCHAR* argv[])
{
    std::string text;
    cin >> text;
    int n = text.size();
    std::string first_array[sizeof(text) / sizeof(text[0])];

    for (int i = 0; i < text.size();i++)
    {
        first_array[i] = text.substr(i, n - i);
    }

    int T = sizeof(first_array) / sizeof(first_array[0]);
    sort(first_array, first_array + T);

    cout << endl << "The sorted tree:" << endl;
    for (int j = 0; j < sizeof(first_array) / sizeof(first_array[0]); j++)
        cout << j+1 << " | " << first_array[j] << endl;
}

That is my code. And for example, if the user inputs "hello", then the program should and I want it to show me this:

1 | ello
2 | hello
3 | llo
4 | lo
5 | o

But, it is showing me this instead (which is wrong and is NOT what I want):

1  |
2  |
3  |
4  |
5  |
6  |
7  |
8  |
9  |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | ello
25 | hello
26 | llo
27 | lo
28 | o

1 Answers1

1

sizeof(std::string) reports the size of the C++ string object (which is, apparently, 28 bytes large), which has nothing to do with the actual length of the string it contains. Use the ".size()" member function for the amount of characters contained in the string and sizing your array.

An alternative would be to use std::vector<std::string> and let it sort out the memory management:

std::vector<std::string> first_array;
for (int i = 0; i < text.size();i++)
         first_array.push_back( text.substr(i, n - i) );

For completeness' sake, here's a working program:

std::string text;
cout << "Please enter your text: ";
cin >> text;
std::vector<std::string> first_array;

for (int i = 0; i < text.size();i++)
    first_array.push_back( text.substr(i, n - i) );

sort(first_array.begin(), first_array.end());

cout << endl << "Suffix Tree (alphabetical order):" << endl;

std::vector<std::string>::iterator  ptr;
for(ptr=first_array.begin(); p!=first_array.end(); ptr++)
    cout << *ptr;
cout << endl;
emvee
  • 4,371
  • 23
  • 23
  • std::sort(first_array.begin(), first_array.end()) for in-place sort. See e.g. http://www.cplusplus.com/reference/algorithm/sort/ – emvee Feb 19 '15 at 11:07
  • Then you're declaring a C-style array of 20 std::string objects. – emvee Feb 19 '15 at 11:13
  • You don't. That's why you use "std::vector" and let the ".push_back()" allocate the elements for you. Then first_array.size() will tell you how many elements there are in the vector, after you're done appending all the suffixes. ["vector" is C++ speak for 'array', for all practical purposes] – emvee Feb 19 '15 at 11:19