I want to update vector 'v' so that I can iterate from count 0-100.
I know this is not allowed, but what if I want to do this only? Is there any way?
int main() {
// your code goes here
vector<int> v;
v.push_back(1);
int count = 0;
for(int elem: v){
if(count<100)
v.push_back(count);
count++;
}
for(int elem: v)
cout << elem << endl;
return 0;
}
The output is:
1
0
In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .
Yes you can. The standard mandates that the memory in a std::vector is contiguous.
Therefore, array of vectors is two dimensional array with fixed number of rows where each row is vector of variable length. Each index of array stores a vector which can be traversed and accessed using iterators. Insertion: Insertion in array of vectors is done using push_back() function.
As you can see from the definition of the range-based for loop, the end_expr does not update between iterations. Therefore you only have one iteration. push_back
invalidates v.end()
(which is what end_expr is as described in the linked page), so what you have is actually undefined behaviour.
The arguably simplest way to fill vector with 0..100 would be:
vector<int> v(101);
std::iota(v.begin(), v.end(), 0);
You should use this code instead
int count = 0;
while (v.size() < 100) {
v.push_back(count++)
}
Modifying vector while iterate through it is not allowed
Best efective way for this operation
vector<int> v;
v.resize(100);
for(unsigned int i = 0; i < v.size(); i++)
{
v[i] = i;
}
same as above.
using your code :
for(int elem: v){
if(count<100)
v.push_back(count);
count++;
}
is like using this :
int i = v.size();
for(int j = 0; j < i; j++){
v.push_back(j);
}
I don't really know why... v.size() might be keep in memory for optimization and data protection
Edit after OP comment :
Try this
int i = v.size();
for(int j = 0; j < i; j++){
if(j<100)
i = v.size();
v.push_back(count);
}
A range-based for loop produces code similar to this:
{
auto && __range = range_expression ;
for (auto __begin = begin_expr,__end = end_expr; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
As you can see the range will not be updated as you're iterating over your container.
Additionally you're most likely ending up with undefined behaviour because as you're pushing back values to your vector
these iterators will be invalidated in case of a resize.
See @user2079303 for a better way to fill your vector
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With