用于迭代“在每对连续的元素对之间"的惯用法. [英] Idiom for iterating "between each consecutive pair of elements"

查看:46
本文介绍了用于迭代“在每对连续的元素对之间"的惯用法.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人在某个时候都会遇到此问题:

Everyone encounters this issue at some point:

for(const auto& item : items) {
    cout << item << separator;
}

...,您最终会得到一个多余的分隔符.有时它不是在打印,而是执行其他操作,但是同一类型的连续操作需要一些分隔符操作-但最后一个不需要.

... and you get an extra separator you don't want at the end. Sometime it's not printing, but, say, performing some other action, but such that consecutive actions of the same type require some separator action - but the last doesn't.

现在,如果您使用老式的循环和数组,就可以了

Now, if you work with old-school for loops and an array, you would do

for(int i = 0; i < num_items; i++)
    cout << items[i];
    if (i < num_items - 1) { cout << separator; }
}

(否则,您可以特例地将循环中的最后一个项目放在首位.)如果您有任何允许无损迭代器的内容,即使您不知道其大小,也可以执行以下操作:

(or you could special-case the last item out of the loop.) If you have anything that admits non-destructive iterators, even if you don't know its size, you can do:

for(auto it = items.cbegin(); it != items.cend(); it++) {
    cout << *it;
    if (std::next(it) != items.cend()) { cout << separator; }
}

我不喜欢最后两个的美学,喜欢范围循环.我能否获得与后两个相同的效果,但使用更多漂亮的C ++ 11ish构造?

I dislike the aesthetics of the last two, and like ranged for loops. Can I obtain the same effect as with the last two but using more spiffy C++11ish constructs?


为了进一步扩展这个问题(例如,除了这个问题),我想说的是,我也不想明确表示特殊的意思,大小写第一个或最后一个元素.这是一个实现细节",我不想被打扰.因此,在虚构的C ++中,可能类似于:


To expand the question further (beyond, say, this one), I'll say I would also like not to expressly have special-case the first or the last element. That's an "implementation detail" which I don't want to be bothered with. So, in imaginary-future-C++, maybe something like:

for(const auto& item : items) {
    cout << item;
} and_between {
    cout << separator;
}

推荐答案

我的方式(不带其他分支)是:

My way (without additional branch) is:

const auto separator = "WhatYouWantHere";
const auto* sep = "";
for(const auto& item : items) {
    std::cout << sep << item;
    sep = separator;
}

这篇关于用于迭代“在每对连续的元素对之间"的惯用法.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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