Using std :: vector as the key for std :: map does not return end () when not found and uses reserve ()

I use the C ++ STL Map and Vector classes in a program where I have a map that takes a vector as a key pointing to an integer. Typically, when searching the map for a value, if the value is not found, myMap.find () returns myMap.end ().

My problem arises when I try to pre-allocate space in my vector (to prevent a constant resizing when I use them) using myVector.reserve (int). For some reason, searching for my map for a vector that I know will not be returned will not return myMap.end () when space has been allocated for the vector I'm looking for, regardless of whether I really fill vector or not (example 1).

However, simply inserting objects into the vector that I want to find will give me the correct location myMap.end () when the vector is not on the map (example 2).

Example 1:

#include <map>
#include <vector>
#include <iostream>

using namespace std;

int main(){

 vector<int> v, v1;
 v.reserve(1);
 v1.reserve(1);
 v[0] = 1;
 v1[0] = 2;
 map<vector <int>, int> m;

 m.insert(make_pair(v, 0));

 cout << int(m.find(v1) == m.end());
}

Returns 0

Example 2:

#include <map>
#include <vector>
#include <iostream>

using namespace std;

int main(){

 vector<int> v, v1;
 v.reserve(1);
 v[0] = 1;
 v1.push_back(5);
 map<vector <int>, int> m;

 m.insert(make_pair(v, 0));

 cout << int(m.find(v1) == m.end());
}

Returns 1

I want to be able to reserve space in my vector, but it seems that the only way to make the map work as shown is to insert elements on the fly and dynamically resize the vector. It's right? Are there any workarounds? Can someone explain this (obvious) behavior aberrant?

+3
source share
1 answer

Firstly, this code does not do what you think. reserve () does not resize ().

vector<int> v;
v.reserve(100);
v[0] = 1;  //undefined
cout << v.size(); //prints 0

: , "" , v v1 , ==, <= .. , segfault , . , , ( ).

<= = > , , , , .

-, , ==. , : lt = = . .

Foo foo1(1);
Foo foo2(2);

map<Foo, int> m;
m.insert(makepair(foo1, 1));
m.find(foo2) == m.end(); //will be true iff foo1 <= foo2 && foo2 <= foo1
//even if foo1 != foo2 or !(foo1 == foo2)

Foo, (foo1 <= foo2 & foo2 <= foo1), somemap.insert(makepair (foo1, 1)); somemap.find(foo2) foo1, foo1!= foo2 ! (foo1 == foo2).

-, < = ? , . , "", <= , , - , .

+4

All Articles