簡體   English   中英

訪問 C++ 中向量中的 map 元素

[英]Access map elements in a vector in C++

是否可以在不遍歷for(std::map<std::string, double>::iterator it = elem.begin(); it.= elem;end(); ++it)的情況下訪問map中的元素for(std::map<std::string, double>::iterator it = 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;
}

output:

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

可以用一種不太冗長的方式:

    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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM