std::map
I want to find out if the key already exists or not
What should I do?
My code is making an error
typedef map<string,string>::iterator mi;
map<string, string> m;
m.insert(make_pair("f","++--"));
pair<mi,mi> p = m.Equal_range("f"); // I'm not sure if I can use Equal_range
cout << p.first;//error here
The function that investigates the key is map::find().
if ( m.find("f") == m.end() ) {
// // not found
} } else {
// // found
}
If you're just investigating and not an iterator, it might be more convenient to use std:count().
Originally, count()
is a function of counting how many elements there are
std::map
Returns 1
if key
exists and 0
if not, because each element in the container is unique.
Therefore, if you just do the test, please write as follows.
if ( m.count(key) ){}
© 2024 OneMinuteCode. All rights reserved.