Append element to array

Nov 29, 2012 at 3:52am
Hello. I'm new at C++ coming from a good experience with Python.

I have an array

 
string x[] = {"a", "b", "c"};


I would like to add an element to said array. In Python I would do

 
x.append("d")


How do I do something like this in C++? How can I add an entry to the end of an array?

Thanks!
Last edited on Nov 29, 2012 at 3:52am
Nov 29, 2012 at 3:57am
The kind of array you're thinking of is called "std::vector" in C++:

1
2
std::vector<std::string> x = {"a", "b", "c"};
x.push_back("d");


online demo: http://ideone.com/Zc1JlU

(caveat: old compilers couldn't use this handy initialization syntax, you had to insert "a", "b", and "c" with indivudual push_backs or use an intermediate array: string a[] = {"a", "b", "c"}; vector<string> x(a, a+3); )
Last edited on Nov 29, 2012 at 3:57am
Nov 29, 2012 at 4:06am
Tnx ! for the above. !

I've always used the intermittent array, I'll try this from now-on.
Nov 29, 2012 at 4:09am
@Cubbi Thank you! That is exactly what I need.
Nov 29, 2012 at 4:11am
Initializer lists are a feature of C++11. You may need to set up your compiler to use them (mine is turned off by default)
C arrays (those defined by square brackets) cannot be resized
Nov 29, 2012 at 5:15am
i can resize it.
http://www.cplusplus.com/forum/lounge/86408/
Topic archived. No new replies allowed.