Code:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct letter
{
char character;
letter(char init = 0): character(init) {}
};
int main()
{
vector<letter> nodes;
string hello = "Hello World";
for(int i=0; i<hello.length(); i++)
nodes.push_back(letter(hello[i]));
for(int j=0; j<nodes.size(); j++)
cout << nodes[j].character;
return 0;
}
What was wrong? Let's take a look:
>clrscr();
Silly and nonportable, but I'll ignore it this time.
>vector<letter> *nodes;
Note that this is a pointer to a vector. If you really want a pointer to a vector then you need to use new to actually create it. If you want a vector of pointers to letter then this is the correct declaration:
Code:
vector<letter *> nodes;
Of course, that complicates your usage without any obvious benefit for this program, so I just changed it to a vector of letters.
>for(int i=0; i<12; i++)
std::strings need not be null terminated, you're walking past the end with this loop. 11 would be correct, and hello.length() would be much better.
>nodes->character.pushback(hello[i]);
This is all kinds of wrong. nodes is a pointer to a vector, so the arrow operator is correct (assuming it points to something valid), but character isn't a member of nodes, it's a member of letter. Without an appropriate constructor defined, you would need to do this:
Code:
nodes->push_back(letter());
nodes->back().character = hello[i];
So defining a default and single argument constructor makes a lot of sense.
>cout << *nodes[j]->character;
Operator precedence is a pain. Remember that if you want indirection before indexing, surround the indirection in parens:
Code:
cout << (*nodes)[j]->character;