首页 > 解决方案 > 如何检测地图迭代器中的最后一个元素

问题描述

我希望能够在我的地图迭代器中检测到最后一次迭代。我将如何实现这一目标?

class JSON {
public:
    static void stringify(map<string, string> data)
    {
        string base;

        base += "{ ";

        for (map<string, string>::iterator it = data.begin(); it != data.end(); ++it)
        {
            cout << it->first.c_str() << " => " << it->second.c_str() << endl;
        }
    }
};

标签: c++stl

解决方案


您可以像这样使用std::prev :

    for(auto it = data.begin(); it != data.end(); ++it)
    {
        if(it == std::prev(data.end()))
        {
            // this is the last iteration
        }

        std::cout << it->first << " => " << it->second << '\n';
    }

std::prev从其参数返回前一个迭代器。


推荐阅读