-
struct + vector = fun
I am trying to push individual characters from a string to the back of a vector of structs.. i'm just not sure of the correct syntax to properly pushback to the correct struct attribute.
Code:
#include<iostream>
#include<string>
#include<vector>
#include<conio.h>
using namespace std;
struct letter
{
char character;
};
int main()
{
clrscr();
vector<letter> *nodes;
string hello = "Hello World";
for(int i=0; i<12; i++)
nodes->character.pushback(hello[i]);
for(int j=0; j<nodes->size(); j++)
cout << *nodes[j]->character;
return 0;
}
compiler errors thus far:
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
contest.cpp:
Error E2316 contest.cpp 26: 'character' is not a member of 'vector<letter,allocator<letter> >' in fu
nction main()
Warning W8012 contest.cpp 28: Comparing signed and unsigned values in function main()
Error E2288 contest.cpp 30: Pointer to structure required on left side of -> or ->* in function main
()
*** 2 errors in Compile ***
thanks in advance :D
-
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;