如何使用循环缩短条件

How to shorthen a condition using a loop?

本文关键字:条件 循环 何使用      更新时间:2023-10-16

我有六个组件数组,我想确保如果用户正在初始化组件的值,他/她不会给出 2 个或更多相同的数字。

while (tab[i] == tab[i - 1] || tab[i] == tab[i - 2] || tab[i] == tab[i - 3] || tab[i] == tab[i - 4] || tab[i] == tab[i - 5])
    {
        cout << "Liczby nie moga sie powtarzac! Sproboj jeszcze raz: ";
        cin >> tab[i];
    }

我试着像这样做:

while (for (int m = 1; m < 6; ++m)
   {  
     tab[i] == tab[i - m];
   }

但它不起作用:/

您可以使用

std::find

while (std::find(&tab[i - 5], &tab[i], tab[i]) != &tab[i])
{
}

但是,就像您的代码一样,这仅适用于第六个数字。

要读取六个没有重复的数字,您可以执行以下操作:

int tab[6] = {0};
int i = 0;
while (i < 6) {
    do {
        cin >> tab[i];
    } while (std::find(tab, tab + i, tab[i]) != tab + i);
    i++;
}

使用 lambda:

auto const checkPrevDups = [&] {
    for (int m = 1; m < 6; ++m)
        if(tab[i] == tab[i - m])
            return true;
    return false;
};
while (checkPrevDups()) {
    // ...
}

您也可以将 lambda 直接嵌入到条件中,但这看起来可能有点臃肿。

在我看来

,std::any_of 就是你要找的(假设 C++11(:

#include <algorithm>
auto check = [&](int el){
    return tab[i] == el;
};
while( std::any_of(&tab[i-5], &tab[i], check) )
{
    cout << "Liczby nie moga sie powtarzac! Sproboj jeszcze raz: ";
    cin >> tab[i];
}

将检查循环放入一个函数中 - 更好的是,使用已经存在的函数(例如 std::count(:

while (std::count(tab+i-5,tab+i,tab[i]) != 0)
{
    std::cout << "Liczby nie moga sie powtarzac! Sproboj jeszcze raz: ";
    std::cin >> tab[i];
}

如果tabstd::vector甚至std::deque,也可以使用的更通用的版本是这样的:

while (std::count(std::begin(tab)+i-5,std::begin(tab)+i,tab[i]) != 0)

使用无序集合

#include <unordered_set>
int main(){
    std::unordered_set<int> set;
    int input = 5;
    auto got = set.find(input);
    if(got == set.end()){
        //input is not found
        //add to set
        set.insert(input);
    }
    return 0;
}

停留在 while 循环中,直到扫描所有值:

int i = 0;
while(i < 6)
{
    std::cin >> tab[i];
    for(int j = 0; j < i; ++j)
    {
        if(tab[i] == tab[j])
            goto DUPLICATE; // exit double loop
    }
    ++i; // no duplicates found, next input
    continue;
    DUPLICATE:
    std::cout << "Liczby nie moga sie powtarzac! Sproboj jeszcze raz: ";
}

编辑:使用已经存在的代码总是更好 - 从molbdnilo窃取std::find

int i = 0;
while(i < 6)
{
    std::cin >> tab[i];
    if(std::find(tab, tab + i, tab[i]) == tab + i)
        std::cout << "Liczby nie moga sie powtarzac! Sproboj jeszcze raz: ";
    else
        ++i;
}

尝试使用嵌套的 for 循环遍历数组。

查看此代码以更好地理解我的意思:

    int array[SIZE] = {1,2,3,4,5};
    for(int i = 0; i < SIZE; i++){ // set our element to check against all other elements
        for(int o = i+1; o < SIZE; o++) // iterate and check new element with our initial element
            if(array[i] == array[o]) // collision
                cout<<"ERROR"<<endl;
                // put code here to make user re-input value
            else
                cout<<("ok")<<endl;
    }

上面的代码不会打印"错误">

但是,如果将数组中的最后一个索引替换为"1":

int array[SIZE] = {1,2,3,4,1};

您将看到此算法检测到它并打印"错误">