使用key获取对std::map节点的引用



如何使用键std::pair<key_type, value_type>& node = map_obj[key];获取对std::map节点的引用。我知道std::mapoperator[]返回对值部分的引用,但我想引用整个节点(std::pair<key_type, value_type>&)。

您可以使用以下命令。当然,这段代码假定键存在于映射()中。mymap.find("b") != mymap.end())。另外,数组对的第一个成员必须是常量(因为改变它的值会使映射无效)。

#include <iostream>
#include <map>
int main()
{
std::map<std::string, int> mymap = {{"a",5}, {"b", 7}};
std::pair<const std::string, int> &mypair = *mymap.find("b");
std::cout << mypair.first<< " " << mypair.second << std::endl;
return 0;
}

最新更新