如何访问向量中的元素>>

问题描述 投票:0回答:3

我在向量容器中访问map和pair的成员时遇到了麻烦。我试图使用for循环和矢量迭代器来尝试访问vector中的元素,但没有运气。这是我的代码:

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
3个回答
0
投票

尝试:

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

0
投票

要访问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;
   }
}

0
投票

您可以像这样访问它:

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';
    }
© www.soinside.com 2019 - 2024. All rights reserved.