| smrt (6) | ||||
|
Hello again. My assignment is to create a program that reads a text file and displays a list of the top ten most common words in it. To do this, I read the file into a vector and then play around with the vector to get the output I want. My problem lies in the instructions I am given:
I am doing just fine storing all of the text into a vector, and I don't really know what they mean by this. My problem is that I get pointers and references mixed up pretty badly. I have gone about placing *'s and &'s on every variable and in every combination I can imagine and am not getting anywhere. The textbook is no help and I haven't found the documentation very applicable. Here is the code in question:
It works like a charm, just not in the way the assignment wants. Help is always appreciated. | ||||
|
|
||||
| Zhuge (2880) | |
| So firstly, you need to make a vector of pointers to strings. Do you know how to declare a variable of that type? | |
|
|
|
| smrt (6) | |
| Would that be declaring it as vector<string*>? | |
|
|
|
| Zhuge (2880) | |
|
Yeah, that's it. Now by the above code I assume you already know how to read lines from a file into strings and store them into a vector. The only thing that remains, then, is to convert them to pointers so you can push them onto the vector. How would you do that? (But think carefully; remember that objects are destructed when they go out of scope.) | |
|
|
|
| smrt (6) | |||
|
(You lost me with that last part; we don't go into objects until next chapter. :P) Could I declare a pointer to a string, assign my current string to the pointer, and then load that pointer into the array? Something like:
And I just change my function declaration to return a pointer? | |||
|
|
|||
| Zhuge (2880) | |
|
On line 7, you would need to the address-of operator. You can't simply assign a string to a string*; you need to get the address of it first. However, while it would compile, it would not work properly because you are storing a pointer to a string that is local to the function, and when the function ends that variable disappears. That leaves the pointer pointing to bad memory; I think you'll need to use dynamic allocation to get around that. | |
|
|
|