简体   繁体   English

如何检查元素是否在C ++中的映射键中?

[英]How can I check if an element is in map keys in C++?

I am wonder if there is a way I can check if an element is included in map keys. 我想知道是否有一种方法可以检查元素是否包含在地图键中。 For example: 例如:

#include<iostream>
#include<map>

using namespace std;

int main()
{

map<char, int> mymap;

mymap['a'] = 1;
mymap['b'] = 2;
mymap['z'] = 26;

// I want to check if 'b' is one of the keys in map mymap.

    return 0;
}

Elements 'a', 'b' and 'z' are the keys of map mymap. 元素“ a”,“ b”和“ z”是地图mymap的键。 I want a command that will return true if element is in keys of a map and false if the elements is not in keys of a map. 我想要一个命令,如果元素在地图的键中,则返回true如果元素不在地图的键中,则返回false I looked around, but could find a quick build-in method that does this. 我环顾四周,但是可以找到一种快速的内置方法来做到这一点。 Did I miss anything? 我有想念吗? Is there a such a method? 有没有这样的方法?

Here is a long way that gets me my desired outcome: 这是让我获得理想结果的长途之路:

#include<iostream>
#include<map>

using namespace std;

bool check_key(map<char, int> mymap, char key_val);

int main()
{

map<char, int> mymap;

mymap['a'] = 1;
mymap['b'] = 2;
mymap['z'] = 26;

char key_val = 'h';

cout<<mymap.find('z')->first<<endl;

cout<<"checking "<< check_key(mymap, 'h')<<endl;
cout<<"checking "<< check_key(mymap, 'b')<<endl;

    return 0;
}

bool check_key(map<char, int> mymap, char key_val){

    for (map<char, int>::const_iterator it = mymap.begin(); it != mymap.end(); ++it ){
        if (key_val == it->first){
            return true;
        }

    }
    return false;

}

Thank You in Advance 先感谢您

只需检查是否mymap.find('b') != mymap.end()

You can check if a key is present by comparing the result of find() to the iterator returned by end() : 您可以通过将find()的结果与end()返回的迭代器进行比较来检查是否存在密钥:

std::map<char, int> my_map;
// add items
std::map<char, int>::iterator found = my_map.find('b');
if (found == my_map.end())
{
  // 'b' is not in the map
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查C ++中的map是否包含来自另一个映射的所有键 - Check if map in C++ contains all the keys from another map C++:如何将键和值传递给构造函数以制作地图而不在构造过程中复制地图的值? - C++: How can I pass keys and values into a constructor to make a map without copying the values of the map during construction? 在地图c ++中有效地检查元素 - Efficiently check element exists in map c++ 检查地图中是否存在元素c ++ - Check if element exists in map c++ 如何检查 C++ map 中的值而不会在“const”成员 function 中出现编译器错误? - How can I check values in a C++ map without getting compiler errors in a “const” member function? 如何在 C++ 中检查时间? - How can I check time in C++? 如何搜索所有地图键C ++ - how to search all map keys c++ C ++如何将结构数组初始化为null,然后在while循环中检查此数组的元素是否为null? - C++ How can I initialize array of structs to null and later check if an element of this array is null in a while loop? 如何使用NCurses阻止C ++中的某些键 - How can I block certain keys in C++ with NCurses 如何检查类数组的元素是否为空? [c ++] - How do I check if an element of an array of classes is empty? [c++]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM