0

How can I add int to my int array. I do not want to set array size, I do not want to use external loop.

int myArray[] = {};
...
if (condition) 
{
    myArray.push(value);
}
2
  • 15
    You can't. The size of an array is fixed. Use an std::vector if you need a dynamic array. Commented Nov 17, 2016 at 14:24
  • @JonathanMee forget it, I'll delete my comments Commented Nov 17, 2016 at 14:46

2 Answers 2

4

As Leon suggests what you're looking for is vector and specifically its push_back method.

You could use it as follows:

vector<int> myArray; // currently size 0

if(condition) {
    myArray.push_back(value); // now resized to 1;
}

EDIT:

You can use an ostream_iterator to print a vector. For example:

copy(cbegin(myArray), cend(myArray), ostream_iterator<int>(cout, " "))
Sign up to request clarification or add additional context in comments.

21 Comments

@JonathanMee A range based for loop automates the iterator protocol just as well. I don't buy that using an algorithm is more readable in this case. (Although I agree that one should prefer re-use of algorithms, this is going a bit too far IMHO)
@StoryTeller I can agree with that, though my personal preference is the copy statement, particularly to the multi-lined for-statement, or even worse the single line for-statement.
@JonathanMee, well, can't argue with preferences :)
@TeodorKolev That's because resultArray is empty.
@TeodorKolev, are you sure? Print the vectors size() first.
|
0

You cannot use push into an array. I would suggest you to use lists or vectors if you don't want to set any size.

2 Comments

list have sub-performance most of the time, except in a truly parallel setting. It's better to turn to std::vector by default.
Also you should prefer linking to cppreference.com over cplusplus.com (the latter one is occasionally inaccurate)

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.