在使用foreach语法进行迭代时,如何检查我是否在最后一个元素上

Lla*_*don 19 c++ foreach c++11

例如:

for( auto &iter: item_vector ) {
     if(not_on_the_last_element) printf(", ");
}
Run Code Online (Sandbox Code Playgroud)

要么

for( auto &iter: skill_level_map ) {
     if(not_on_the_last_element) printf(", ");
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 33

你不能真的.这就是范围的一点,是你不需要迭代器.但是,如果不是第一个,你可以改变你打印逗号的逻辑来打印它:

bool first = true;
for (auto& elem : item_vector) {
    if (!first) printf(", ");
    // print elem
    first = false;
}
Run Code Online (Sandbox Code Playgroud)

如果这是循环的意图无论如何.或者您可以比较地址:

for (auto& elem : item_vector) {
    if (&elem != &item_vector.back()) printf(", ");
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 很酷的技巧(第一个片段),**+1**! (2认同)

Bil*_*nch 7

没有好方法.但是如果我们可以轻松访问容器的最后一个元素......

std::vector<int> item_vector = ...;
for (auto & elem : item_vector) {
    ...
    if (&elem != &item_vector.back())
        printf(", ");
}
Run Code Online (Sandbox Code Playgroud)


qua*_*ana 6

这就像一个状态模式。

#include <iostream>
#include <vector>
#include <functional>

int main() {
    std::vector<int> example = {1,2,3,4,5};

    typedef std::function<void(void)> Call;
    Call f = [](){};
    Call printComma = [](){ std::cout << ", "; };
    Call noPrint = [&](){ f=printComma; };
    f = noPrint;

    for(const auto& e:example){
        f();
        std::cout << e;
    }

    return 0;
}


Output:

1, 2, 3, 4, 5
Run Code Online (Sandbox Code Playgroud)

第一次通过f点 tonoPrint只用于使fthen 指向printComma,因此逗号仅在第二个及后续项目之前打印。


Tem*_*Rex 5

最好使用“ Loop and Half ”结构编写以下类型的循环:

#include <iostream>
#include <vector>

int main()
{
    auto somelist = std::vector<int>{1,2,3,4,5,6,6,7,8,9,6};

    auto first = begin(somelist), last = end(somelist);
    if (first != last) {                // initial check
        while (true) {
            std::cout << *first++;     
            if (first == last) break;   // check in the middle
            std::cout << ", ";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实时示例打印

1,2,3,4,5,6,6,7,8,9,6

即在最后一个元素的末尾没有分隔符。

中间的检查与do-while(预先检查)或for_each /基于范围的for(结束检查)有什么不同。试图在这些循环上强制使用常规的for循环将引入额外的条件分支或重复的程序逻辑。