问题描述
我有地图数据结构 map<string,vector< pair<string,string> >
,其中地图 key
是 string
数据类型,值是 vector<pair<string,string> >
数据类型。
如果我尝试使用字符串数据类型的 find
值执行 count
或 key
操作。我确实遇到了编译问题。
为什么会这样?我应该能够在地图上执行 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::__cxx11::basic_string<char> > > > >}’ to non-scalar type ‘testAttribute_map {aka std::map<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";
}