gpt4 book ai didi

c++ - 嵌套 map ,访问内部 map 值

转载 作者:太空狗 更新时间:2023-10-29 20:12:38 25 4
gpt4 key购买 nike

例如我有这样一张 map :

    map<string , map <int , int>> example;

和一个迭代器:

    map<string , map <int, int>>::iterator iter;
string word;

我想访问内部 map :

  for(iter = example.begin();iter!=example.end;iter++){

iter = Map.find(word);
iter -> second //
}

如果 iter->second ==4 - 它不正确,我应该如何访问内部映射,例如或者我可以做 (iter->second)->second ???你能给我一个建议吗?我不明白迭代器给了我一对 (int,int) 所以我试着做另一个迭代器 map::iterator i;并赋值 iter->second = i,但这对我没有帮助;

最佳答案

对于复杂类型使用 typedef 它会让你的生活更轻松:

typedef std::map< int, int > Ints;
typedef std::map< std::string, Ints > String2Ints;

String2Ints example;
std::string word;

String2Ints::iterator it = example.find( word );
if( it != example.end() ) {
Ints &innerMap = it->second;
Ints::iterator innerit = innerMap.find( 4 );
if( innerit != innerMap.end() )
std::cout << "found value for word " << word << " 4 - " << innerit->second << std::endl;
}

您的循环和内部查找也不正确,您应该遍历 map 或通过 find() 搜索值,您在代码中所做的事情没有任何意义(技术上无限循环如果找到单词)

关于c++ - 嵌套 map ,访问内部 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26366527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com