tex
tex

Reputation: 1

Why vector assignment changes the assigned vector

Case 1

void insert(map<string, vector<int>> &y,const string &x)
{
vector<int> v=y[x];
if(!y.count(x)>0)
  {
    ...
  }
}

Case 2

void insert(map<string, vector<int>> &y,const string &x)
{
//vector<int> v=y[x];
if(!y.count(x)>0)
   {
   ...
  }
}

In the first case, the if statement is true. In the second case, the if is false. In both cases at first the size of y[x] was zero. But in the first case after assigning y[x] to v, the size of y[x] changes to 1.

How does this happen? And also how can we assign y[x] to v with out affecting y[x]?

Upvotes: 0

Views: 68

Answers (1)

us2012
us2012

Reputation: 16253

Because map::operator[] creates a key-value pair with default-constructed value if the key passed to it does not yet exist.

If you don't want that, either use map::at (which will throw an exception if the key does not exist, so you would have to handle that) or map::find (which returns an iterator to the element with that key, or map::end if there is no such element).

Upvotes: 2

Related Questions