【问题标题】:How to access element in vector<map<first, pair<K,V>>>如何访问vector<map<first, pair<K,V>>>中的元素
【发布时间】:2016-05-11 04:53:41
【问题描述】:

我在访问矢量容器中的地图和配对成员时遇到问题。我尝试使用 for 循环和向量迭代器来尝试访问向量内的元素,但没有运气。这是我的代码:

typedef int lep_index;
typedef double gold;
typedef double pos;
map<lep_index, pair<gold, pos>> lep;
vector <map<lep_index, pair<gold, pos>>>  leps;

//initialize lep and leps
for (int i = 1; i <= 10; i++) {
    lep[i - 1] = pair<gold, pos>(MILLION, i * MILLION);
    leps.push_back(lep);
}

//I can access lep's elements by doing this
for (auto &i : lep) {
            cout << i.first << ": " << i.second.first << ", " << i.second.second << endl;
        }

//but when i try with vector...
for (vector <map<lep_index, pair<gold, pos>>>::iterator it = leps.begin(); it != leps.end; it++) {
            cout << it->
        }
//I cannot use it pointer to access anything

我不知道我在这里做错了什么或正确的方法,所以希望我能得到一些帮助。

【问题讨论】:

    标签: c++ dictionary vector std-pair


    【解决方案1】:

    试试:

    for (auto& map : leps) {
        for (auto& i : map) {
                cout << i.first << ": " << i.second.first
                     << ", " << i.second.second << endl;
        }
    }
    

    【讨论】:

    • 哦我明白了,所以在第一个循环之后,它代表 map> ?
    • 是的,完全正确。您的第一个循环只是遍历向量的项目并一个一个地返回地图。所以每张地图都需要另一个循环。
    【解决方案2】:

    要访问leps 的内容,您需要另一个for 循环。

    for (vector <map<lep_index, pair<gold, pos>>>::iterator it = leps.begin(); it != leps.end; it++)
    {
       auto& lep = *it;         // lep is a map.
       for ( auto& item : lep ) // For each item in the map.
       {
          cout << item.first << ": " << item.second.first << ", " << item.second.second << endl;
       }
    }
    

    【讨论】:

      【解决方案3】:

      你可以这样访问它:

      std::cout << vec[0][100].first << " " << vec[0][100].second << '\n';
      

      其中 0 是向量中的第一个元素,100 是键。

      如果你想访问每个元素,range-based for loop 很方便:

      for (const auto& i : vec)
          for (const auto& j : i) {
              std::cout << "Key: " << j.first << '\n';
              std::cout << "pair: " << j.second.first << " " << j.second.second << '\n';
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-04
        • 1970-01-01
        • 1970-01-01
        • 2011-03-06
        • 2021-06-17
        • 1970-01-01
        • 2019-10-10
        • 1970-01-01
        相关资源
        最近更新 更多