gaoxinge
gaoxinge

Reputation: 461

vector with zero size after insert an empty vector

vector<int> a;
vector<vector<int>> b;
cout << b.size() << endl;  // 0
b.insert(b.begin(), a);
cout << b.size() << endl;  // 1
vector<vector<int>> b;
cout << b.size() << endl;  // 0
b.insert(b.begin(), {});
cout << b.size() << endl;  // 0

My questions:

  1. What is the difference between example 1 and example 2?
  2. Why is vector b's size zero after insert in example 2?

Upvotes: 0

Views: 338

Answers (2)

eerorika
eerorika

Reputation: 238311

What is the difference between example 1 and example 2?

They have arguments of different type. First passes a vector as an argument and invokes following overload:

constexpr iterator insert(
    const_iterator pos,
    const T& value);

Second passes an initializer list and invokes the following overload:

constexpr iterator insert(
    const_iterator pos,
    std::initializer_list<T> ilist);

Why is vector b's size zero after insert in example 2?

Because you insert an empty initializer list. Since the initializer list doesn't contain any elements, no elements are inserted. You could insert a single value initialized element like this:

b.insert(b.begin(),
    {            // list of elements
        {},      // first element
    }
);

Or you could use following syntax to call the other overload:

b.insert(vector<int>{});

Upvotes: 3

In the first example, you copy and insert a vector into the beginning of the other vector. Though the vector a is empty, it's still a valid variable, so it's inserted and the size of vector b changes. In the second example, you insert an empty initializer list. It doesn't contain any elements, so the size of the vector doesn't change, no elements are inserted.

Upvotes: 0

Related Questions