C++ 如何创建一个for循环来运行除特定值之外的所有值0-n?

C++ 如何创建一个for循环来运行除特定值之外的所有值0-n?,c++,C++,它当前终止于j=5,我希望它以某种方式跳过j=5迭代,并继续到jfor(int j=0;jfor(int j=0;j

它当前终止于j=5,我希望它以某种方式跳过j=5迭代,并继续到j
for(int j=0;j
for(int j=0;j<10;j++){
如果(j==5)
继续;

例如,您可以用以下方式编写

for ( int j = 0; j < 10 ; ++j )
{

    if ( j != 5 ) cout << "loop working for j = " << j << endl;

}
for(int j=0;j<10;++j)
{

如果(j!=5)不能那么,还有另一个版本

for(auto j: std::initializer_list<int>{0, 1, 2, 3, 4, 6, 7, 8, 9}) {
}
for(自动j:std::初始值设定项列表{0,1,2,3,4,6,7,8,9}){
}

您还可以在专用函数中增加计数器。以下是lambda函数的示例:

#include <iostream>

int main()
{
    auto const incrementSkippingFive = [](int& j)
    {
        if (j == 4)
        {
            j += 2;
        }
        else
        {
            ++j;
        }
    };

    for (int j = 0; j < 10; incrementSkippingFive(j))
    { 
        std::cout << "loop working for j = " << j << "\n";
    }
}
#包括
int main()
{
自动常量递增SkippingFive=[](int&j)
{
如果(j==4)
{
j+=2;
}
其他的
{
++j;
}
};
对于(int j=0;j<10;递增跳过五(j))
{ 

STD:CUT

当然C++应该总是尽可能地表达:

int main()
{
    for (auto i : everything.from(1).to(9).except(5))
    {
        std::cout << i << std::endl;
    }
}
你是认真的吗

;-)

for ( int j = 0; j < 10 ; j += ( j == 4 ) + 1 )
{

    cout << "loop working for j = " << j << endl;

}
for(auto j: std::initializer_list<int>{0, 1, 2, 3, 4, 6, 7, 8, 9}) {
}
#include <iostream>

int main()
{
    auto const incrementSkippingFive = [](int& j)
    {
        if (j == 4)
        {
            j += 2;
        }
        else
        {
            ++j;
        }
    };

    for (int j = 0; j < 10; incrementSkippingFive(j))
    { 
        std::cout << "loop working for j = " << j << "\n";
    }
}
int main()
{
    for (auto i : everything.from(1).to(9).except(5))
    {
        std::cout << i << std::endl;
    }
}
#include <iostream>
#include <vector>
#include <algorithm>

struct range
{
    range(int x, int y)
    {
        while (x < y) {
            values.push_back(x++);
        }
    }

    void remove(int z)
    {
        values.erase(std::remove(std::begin(values),
                                 std::end(values), z),
                     std::end(values));
    }

    range except(int z) const {
        auto result = *this;
        result.remove(z);
        return result;
    }

    auto begin() const {
        return std::begin(values);
    }

    auto end() const {
        return std::end(values);
    }

    std::vector<int> values;
};

struct from_clause
{
    int x;

    range to(int y) const { return range(x, y + 1); }
};

struct range_builder
{
    from_clause from(int n) const { return from_clause{n}; }

};

constexpr range_builder everything {};
1
2
3
4
6
7
8
9