提问者:小点点

用C++访问向量中的映射元素


是否可以访问map中的元素而不迭代for(std::map::iteratorit=elem.begin();it!=elem.end();++it)循环?

#include <iostream>
#include <vector>
#include <map>

int main()
{
    std::vector<std::map<std::string, int>> v;
    for (auto ii = 0; ii < 3; ii++)
    {
        std::map<std::string, int> _map;
        _map["type"] = ii;
        v.push_back(_map);
    }
    
    for(auto elem : v)
    {
       std::cout << elem["type"];
       for(std::map<std::string, int>::iterator it = elem.begin(); it != elem.end(); ++it)
       {
           std::cout << " Keys: " << it->first << std::endl;
       }
    }        
    return 0;
}

输出:

0 Keys: type
1 Keys: type
2 Keys: type

共1个答案

匿名用户

可以用一种不那么冗长的方式:

    std::map<std::string, int> m;
    m["t1"]=1;
    m["t2"]=2;
    m["t3"]=3;

    for(auto pair: m){
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|访问|向量|中|映射|元素)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?