微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在地图 C++ 上执行查找/计数操作

如何解决在地图 C++ 上执行查找/计数操作

我有地图数据结构 map<string,vector< pair<string,string> >,其中地图 keystring 数据类型,值是 vector<pair<string,string> > 数据类型。

如果我尝试使用字符串数据类型的 find 值执行 countkey 操作。我确实遇到了编译问题。

为什么会这样?我应该能够在地图上执行 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_mapbool 的隐式转换。

您还需要 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";
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。