这是循环遍历数组的正确方法吗?

Is this the right way to loop through Arrays?

本文关键字:方法 循环 遍历 数组      更新时间:2023-10-16
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;

int main(){
    string Whitelist[4] = {"Stian", "Mathias", "Modaser"};
    for (int x = 0; x < 3; x++){
        cout << x + 1<< ". " << Whitelist[x] << endl;
        if (Whitelist[x] == "Stian" && "Mathias" && "Modaser"){
            cout << "" << Whitelist[x] << " is here" <<  endl;
        }
        else{ cout << "no one is here" << endl; }
    }
    cin.get();
    return 0;
}

//所以基本上我只是尝试遍历数组看看是否有这些名字存在。所以我猜你们几乎可以读懂代码做了什么,因为你们大多数都是专业人士:P。但是当我问我的朋友,他已经编码了1-2年,他说我不能像这样循环数组,并告诉我使用向量。他这话是什么意思?我的代码能工作吗?

这组代码是错误的

if (Whitelist[x] == "Stian" && "Mathias" && "Modaser"){
    cout << "" << Whitelist[x] << " is here" <<  endl;
}

为什么?因为假设if语句的第一个条件的计算结果是true:

if (true && "Mathias" && "Modaser")
{
    //...
}

那么代码就没有意义了。在if语句中,必须分别检查每个条件,如下所示:

if (Whitelist[x] == "Stian" && Whitelist[x] =="Mathias" && Whitelist[x] =="Modaser"){
    cout << "" << Whitelist[x] << " is here" <<  endl;
}

但是因为任何1字符串不能同时是三个名字,这个条件将失败(您使用的是&&)。使用||操作符修复您的代码,就像这样,为您的最终代码(同时,删除<< "",这只是冗余的,不必要的):

if (Whitelist[x] == "Stian" || Whitelist[x] =="Mathias" || Whitelist[x] =="Modaser"){
    cout << Whitelist[x] << " is here" <<  endl;
}

BTW:作为一个建议,使用std::vector<std::string>,而不是一个原始数组,所以你得到更容易和更多的功能比一个数组。最后,数组中还有4个元素,其中一个是未使用的。这可能是一个错别字,所以设置你的数组大小为3

像这样循环遍历数组并没有什么本质上的错误。

我们只能猜测你朋友的意思,但是我可以对你的代码执行我自己的检查。

然而,你有四个数组元素,只循环其中的三个,这可能是一个错误;如果是,这就证明您最好使用迭代器,而不是硬编码可能出错的数字。

此外,您的if条件是错误的:您是指||("或"),而不是&&("answers")吗?你必须完整地写出附加条件,所以:

if (Whitelist[x] == "Stian" || Whitelist[x] =="Mathias" || Whitelist[x] =="Modaser")

我不确定你为什么要比较所有这些值,当它们是数组中唯一的值。除了空的第四个元素;也许你想抓住它。我们不知道,因为你没告诉我们。你的意思是搜索Whitelist而迭代一些其他数组吗?我们无从知晓。也许这就是你朋友真正的意思 ?又一次,我说不出口。

""流式传输到std::cout只是等待资源,实际上没有做任何其他事情。删除它。

最后,有点切题的是,最好不要阻塞等待输入以保持控制台窗口打开。这不是程序的工作。