Vector of strings, what is the easiest way to do it

Mar 12, 2012 at 5:09am
closed account (yh54izwU)
what is the easiest way to get a long list of names using a vector

vector<string> nameslist("Tina","Aaron","Alan","Christi… "Katherine", "Simon", "Nick","Chris","Josh","Jeremy", "Nisa", "Marlon","Will","Eliza","Kat");

is the only thing I could think of but of course that doesn't compile I don't want to individually add each element if I have to how would I do that it has been alot harder than you would think finding this is it just a regular push_back (apparently ints are the only thing used for any sort of array) and no I can't use a regular array it will need to be dynamically allocated
thanks
Mar 12, 2012 at 5:14am
I'm not sure why you couldn't use an array.
1
2
string names[] = {"Tina","Aaron","Alan", /*...*/ "Katherine", "Simon", "Nick","Chris","Josh","Jeremy", "Nisa", "Marlon","Will","Eliza","Kat"};
vector<string> nameslist(names, names+14);
Mar 12, 2012 at 5:36am
closed account (yh54izwU)
Didn't think about doing it like that thanks
Mar 12, 2012 at 7:01am
Individually adding each element is a much better solution:

1
2
3
4
5
vector<string> namelist;
namelist.push_back("Tina");
namelist.push_back("Aaron");
namelist.push_back("Alan");
...


Zhuge's code wouldn't pass our code review, because it is a bug waiting to happen.
Last edited on Mar 12, 2012 at 7:06am
Mar 12, 2012 at 8:43am
Certainly the magic number has to go.

std::vector<std::string> nameslist(names, names+(sizeof(names)/sizeof(names[0]));
Last edited on Mar 12, 2012 at 8:45am
Topic archived. No new replies allowed.