:: To find out if there is a particular key map std.

Asked 1 years ago, Updated 1 years ago, 100 views

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

c++ stl map

2022-09-21 23:16

1 Answers

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) ){}


2022-09-21 23:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.