I want to be able to detect the last iteration within my map iterator. How would I achieve this?
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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用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';
}
Run Code Online (Sandbox Code Playgroud)
std :: prev从其参数返回上一个迭代器。