Home > Enterprise >  Why is std::vector::insert a no-operation with an empty initializer-list?
Why is std::vector::insert a no-operation with an empty initializer-list?

Time:06-10

In the follwoing code:

#include <iostream>
#include <vector>

int main()
{
    std::cout<<"Hello World";
    std::vector<std::vector<int>> v;
    while(v.size() <= 2){
        v.insert(v.begin(),{}); //1
        std::cout << "!";
    }
    return 0;
}

The output is getting increasingly aggressive with every iteration, because the v.size() never increases, despite the insert operation.

However, when the initializer_list has an element in it, or replaced with a temporary, the cycle runs as many times as expected.

...
v.insert(v.begin(),{0}); //1
...
...
v.insert(v.begin(),std::vector<int>()); //1
...

Why is that? Shouldn't there be a compile error if implicit cast fails?

CodePudding user response:

Your code is asking to inert as many items as there are in the initialiser list into the vector. Since there are no items in the initialiser list nothing gets inserted.

I'm not sure what you were expecting instead, perhaps you were expecting a vector to be created from the initialiser list and that vector inserted, i.e.

v.insert(v.begin(),std::vector<int>{})

but that doesn't happen because vector<T>::insert has an overload that takes an initializer_list<T> directly (and which behaves as I described above).

CodePudding user response:

Instead of that loop, do:

v.resize(3);
  • Related