我希望能够检测到我的地图迭代器中的最后一次迭代。我将如何实现?
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;
}
}
};
答案 0 :(得分:5)
您可以像这样使用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从其参数返回上一个迭代器。
答案 1 :(得分:3)
在每个循环迭代中,您可以检查 next 迭代器是否与地图的end()
迭代器匹配,例如:
static void stringify(map<string, string> data)
{
string base;
base += "{ ";
auto it = data.begin();
auto end = data.end();
while (it != end)
{
auto next_it = std::next(it);
if (next_it == end) {
cout << "this is the last iteration!" << endl;
}
cout << it->first << " => " << it->second << endl;
it = next_it;
}
}
或者:
static void stringify(map<string, string> data)
{
string base;
base += "{ ";
auto it = data.begin();
auto end = data.end();
if (it != end)
{
do
{
cout << it->first << " => " << it->second << endl;
auto next_it = std::next(it);
if (next_it == end) {
cout << "that was the last iteration!" << endl;
break;
}
it = next_it;
}
while (true);
}
}
如果您的目标只是避免在第一次或最后一次迭代中将逗号插入到JSON输出中(取决于您要在代码中的哪个位置进行插入),则可以这样做:
static void stringify(map<string, string> data)
{
string base = "{";
auto it = data.begin();
auto end = data.end();
if (it != end)
{
cout << it->first << " => " << it->second << endl;
base += (" \"" + it->first + "\": \"" + it->second + "\"");
while (++it != end)
{
cout << it->first << " => " << it->second << endl;
base += (", \"" + it->first + "\": \"" + it->second + "\"");
}
}
base += " }";
}
答案 2 :(得分:1)
这可以通过以下方式实现:创建索引,在地图的每次迭代中增加索引,然后针对每次迭代将地图的大小与索引进行比较。
class JSON {
public:
static void stringify(map<string, string> data)
{
string base;
int index = 0;
base += "{ ";
for (map<string, string>::iterator it = data.begin(); it != data.end(); ++it)
{
if (data.size() - 1 == index)
{
// Do stuff here
}
cout << it->first.c_str() << " => " << it->second.c_str() << endl;
index++;
}
}
};
答案 3 :(得分:1)
您只需将迭代器边界检查移到循环的主体中即可:
void stringify(map<string, string> data){
string base;
base += "{ ";
for (map<string, string>::iterator it = data.begin();;){
if (it == data.end()){
cout << "Last iteration!";
break;
}
cout << it->first << " => " << it->second << endl;
++it;
}
}
请注意,if
语句中的代码将被调用以生成空映射。