如何迭代map<int, vector <int>>?

How to iterate map<int, vector <int>>?

我有这样的 map:

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

using namespace std;

int main() {
    
    map<int, vector <int>> someMap;
    someMap[5] = {5, 2, 3, 7};
    someMap[151] = {5, 9, 20};

    return 0;
}

我需要找到每个地图值中的最后一个矢量元素。输出必须是这样的:

7
20

谢谢:)

您可以使用std::vector::back成员函数,如下所示:

#include <iostream>
#include <map>
#include <vector>
#include <cassert>
using namespace std;

int main() {
    
    map<int, vector <int>> someMap;
    someMap[5] = {5, 2, 3, 7};
    someMap[151] = {5, 9, 20};
    //iterate through each element of the map
    for(const std::pair<int, std::vector<int>> &myPair: someMap)
    {
        //make sure the vector is not empty
        assert(!myPair.second.empty());
        
        //print the last element in the vector
        std::cout << myPair.second.back() <<std::endl;
    }
    return 0;
}

以上程序的输出为:

7
20

可以看到here.

你一定会喜欢 C++17 structured bindings:

std::map<int, std::vector<int>> m = {
    {5, {5, 2, 3, 7}},
    {151, {5, 9, 20}},
};

for (const auto& [_, v] : m)
{
    if (!v.empty())
    {
        int last = v.back();
    }
}

一些其他资源: