I am pretty new to c++ and was trying to add a new string in C++ array. In Python we can add new items by .append(). Is there any function like this in C++?
2 Answers
in C++ arrays are of a static size. I would recommend including the vector header and replacing the array with a std::vector. vector has a function to add a new entry
9 Comments
Martin Rosenau
It would also be possible to use a pointer instead of an array and to use the
malloc() and realloc() functions.Some programmer dude
@MartinRosenau
malloc and realloc will not work well together with objects.Marijn Kneppers
Indeed, but that would require you to know the index of the data entry. OP is asking for a equivalent function. That would only be possible using a vector.
Martin Rosenau
@Someprogrammerdude That's right. However, in most other programming languages an array of objects is more like
MyClass *myArray[] in C++, not like MyClass myArray[], because you would do: myArray[9] = new MyClass(). And allocating an array whose elements are pointers to objects would work well using realloc().mch
@MartinRosenau no, in C++ you would do
std::vector<MyClass> myArray; and myArray.emplace_back(<constructor arguments>);. |
// Declaring Vector of String type
// Values can be added here using initializer-list syntax
std::vector<std::string> colour {"Blue", "Red", "Orange"};
// Strings can be added at any time with push_back
colour.push_back("Yellow");
https://www.geeksforgeeks.org/array-strings-c-3-different-ways-create/
std::list. If you prefer an arraystd::vectoris the way to go.