0

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++?

1
  • Python does not have arrays, it only has a list. If you want the same complexity on accesses, you can use std::list. If you prefer an array std::vector is the way to go. Commented Oct 5, 2021 at 11:23

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

9 Comments

It would also be possible to use a pointer instead of an array and to use the malloc() and realloc() functions.
@MartinRosenau malloc and realloc will not work well together with objects.
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.
@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().
@MartinRosenau no, in C++ you would do std::vector<MyClass> myArray; and myArray.emplace_back(<constructor arguments>);.
|
1
// 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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.