对地图 c++ 执行 find/count 操作
To perform find/count operation on map c++
我有地图数据结构 map<string, vector< pair<string, string> >
,其中地图 key
是 string
数据类型,值是 vector<pair<string, string> >
数据类型。
如果我尝试使用字符串数据类型的 key
值执行 find
或 count
操作。我遇到了编译问题。
为什么会这样?我应该能够在地图上执行 find
/count
操作!
基本上我有 typedef
地图数据结构如下:-
typedef pair<string,string> attribute_pair;
typedef vector<attribute_pair> attribute_vector;
typedef map<string,attribute_vector> testAttribute_map;
尝试执行查找操作的部分代码片段
testAttribute_map attributes;
string fileName = "Hello.cpp";
if(testAttribute_map iter = attributes.find(fileName))
{
cout<<"success"<<endl;
}
编译错误:
error: conversion from ‘std::map<std::__cxx11::basic_string<char>, std::vector<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > > >::iterator {aka std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, std::vector<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > > > >}’ to non-scalar type ‘testAttribute_map {aka std::map<std::__cxx11::basic_string<char>, std::vector<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > > >}’ requested
if(testAttribute_map iter = attributes.find(fileName))
没有按照您上面的要求从 testAttribute_map
到 bool
的隐式转换。
您还需要 iter
的正确类型并且您需要检查它是否等于 attributes.end()
:
testAttribute_map::iterator iter = attributes.find(fileName);
if(iter != attributes.end())
{
std::cout<<"success\n";
}
或更简单:
if(auto iter = attributes.find(fileName); iter != attributes.end())
{
std::cout<<"success\n";
}
我有地图数据结构 map<string, vector< pair<string, string> >
,其中地图 key
是 string
数据类型,值是 vector<pair<string, string> >
数据类型。
如果我尝试使用字符串数据类型的 key
值执行 find
或 count
操作。我遇到了编译问题。
为什么会这样?我应该能够在地图上执行 find
/count
操作!
基本上我有 typedef
地图数据结构如下:-
typedef pair<string,string> attribute_pair;
typedef vector<attribute_pair> attribute_vector;
typedef map<string,attribute_vector> testAttribute_map;
尝试执行查找操作的部分代码片段
testAttribute_map attributes;
string fileName = "Hello.cpp";
if(testAttribute_map iter = attributes.find(fileName))
{
cout<<"success"<<endl;
}
编译错误:
error: conversion from ‘std::map<std::__cxx11::basic_string<char>, std::vector<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > > >::iterator {aka std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, std::vector<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > > > >}’ to non-scalar type ‘testAttribute_map {aka std::map<std::__cxx11::basic_string<char>, std::vector<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > > >}’ requested
if(testAttribute_map iter = attributes.find(fileName))
没有按照您上面的要求从 testAttribute_map
到 bool
的隐式转换。
您还需要 iter
的正确类型并且您需要检查它是否等于 attributes.end()
:
testAttribute_map::iterator iter = attributes.find(fileName);
if(iter != attributes.end())
{
std::cout<<"success\n";
}
或更简单:
if(auto iter = attributes.find(fileName); iter != attributes.end())
{
std::cout<<"success\n";
}