基于范围的for循环可以知道结尾吗? [英] Can range-based for loops be aware of the end?

查看:50
本文介绍了基于范围的for循环可以知道结尾吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出最小的C ++ 11 STL示例:

Given the minimal C++11 STL example:

set<int> S = {1,2,3,4};
for(auto &x: S) {    
   cout << x;
   cout << ",";
}

有没有一种方法可以检查 x 是否在末尾之前?此示例中的目标是输出 1,2,3,4 而不是最后一个逗号.目前,我使用带有两个迭代器的标准for循环

Is there a way to check if x is the one right before the end? The goal in this example is to output 1,2,3,4 and not the final comma at the end. Currently I use a standard for loop with two iterators,

set<int>::const_iterator itr;
set<int>::const_iterator penultimate_end_itr = --S.end();
for(itr=S.begin(); itr!=penultimate_end_itr;++itr) 
    cout << (*itr) << ',';
cout << (*penultimate_end_itr);

哪个有效,但非常麻烦.有没有办法在基于范围的for循环中进行检查?

Which works, but is terribly cumbersome. Is there a way to do the check within the range-based for loop?

问题的重点是 not ,以打印出逗号分隔的列表.我想知道基于范围的for循环是否对列表中的倒数第二个元素有任何了解(即是否在末尾之前一个).给出了最小的示例,因此我们都有一个共同的代码块可以讨论.

The point of the question is not to print out a comma separated list. I want to know if a range-based for loop has any knowledge of the penultimate element in the list (i.e. is it one before the end). The minimal example was presented so we all have a common code block to talk about.

推荐答案

基于范围的for循环的真正目的是忘记迭代器.因此,它们仅允许您访问当前值,而不能访问迭代器.以下代码会为您做到吗?

The very purpose of range-based for loops is to forget the iterator. As such, they only allow you access to the current value and not the iterator. Would the following code do it for you?

set<int> S = {1,2,3,4};

std::string output;
for(auto &x: S) {    
   if (!output.empty())
       output += ",";
    output += to_string(x);
  }

cout << output;

编辑

另一种解决方案:您可以比较值的地址,而不是比较迭代器(就像使用"normal"循环一样).

Another solution: Instead of comparing iterators (as one would do with "normal" for loops), you could compare the addresses of the values:

set<int> S = {1,2,3,4};
auto &last = *(--S.end());
for (auto &x : S)
{
    cout << x;
    if (&x != &last)
        cout << ",";
}

这篇关于基于范围的for循环可以知道结尾吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆