views:

345

answers:

4

I am trying to write a program that has a vector of char arrays and am have some problems.

char test [] = { 'a', 'b', 'c', 'd', 'e' };

vector<char[]> v;

v.push_back(test);

Sorry this has to be a char array because I need to be able to generate lists of chars as I am trying to get an output something like.

a a a b a c a d a e b a b c

Can anyone point me in the right direction?

Thanks

+4  A: 

You need

char test[] = "abcde";  // This will add a terminating \0 character to the array
std::vector<std::string> v;
v.push_back(test);

Of if you meant to make a vector of character instead of a vector of strings,

std::vector<char> v(test, test + sizeof(test)/sizeof(*test));

The expression sizeof(test)/sizeof(*test) is for calculating the number of elements in the array test.

Tronic
using this how would I push_back another instance of test adding it to the existing vector?
aHunter
+11  A: 

You cannot store arrays in vectors (or in any other standard library container). The things that standard library containers store must be copyable and assignable, and arrays are neither of these.

If you really need to put an array in a vector (and you probably don't - using a vector of vectors or a vector of strings is more likely what you need), then you can wrap the array in a struct:

struct S {
  char a[10];
};

and then create a vector of structs:

vector <S> v;
S s;
s.a[0] = 'x';
v.push_back( s );
anon
+1. You made a good point. :)
Prasoon Saurav
Excellent I did not think of that, need another coffee I think!
aHunter
+3  A: 

Use std::string instead of char-arrays

std::string k ="abcde";
std::vector<std::string> v;
v.push_back(k);
Prasoon Saurav
+1  A: 

You can use boost::array to do that:

boost::array<char, 5> test = {'a', 'b', 'c', 'd', 'e'};
std::vector<boost::array<char, 5> > v;
v.push_back(test);

Edit:

Or you can use a vector of vectors as shown below:

char test[] = {'a', 'b', 'c', 'd', 'e'};
std::vector<std::vector<char> > v;
v.push_back(std::vector<char>(test, test + sizeof(test)/ sizeof(test[0])));
missingfaktor