这是循环遍历数组的正确方法吗?
Is this the right way to loop through Arrays?
#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
只是等待资源,实际上没有做任何其他事情。删除它。
最后,有点切题的是,最好不要阻塞等待输入以保持控制台窗口打开。这不是程序的工作。
- 方法内部但循环仍得到预期的不合格id错误C++
- 在 c++ 中实现嵌套循环的更短方法吗?
- 如何在C++中循环访问未知对象方法?
- EnQueue 方法在循环队列中未正确返回C++?
- C++模板方法中的循环依赖关系
- 为什么这种方法会进入无限循环?
- 编写按初始值循环的循环的更好方法是什么
- 循环遍历标准的正确方法::array<char*, N>
- 类方法 - 数据结构中 For 循环的运行时错误
- 循环依赖,在继承类的情况下使用覆盖方法
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 是否可以在基于范围的 for 循环中使用模板化的开始/结束方法
- 还有其他方法可以为乘法表编写循环以获取运行时值吗?
- 如何避免模板方法的循环依赖
- 使用虚拟变量对 std::vector 内部循环进行切片的最佳方法
- 有什么方法可以在 c++ 中组织"cycling"(循环)数字?
- 我应该避免在循环中重复访问相同的方法吗?
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- 在 C 中并行化嵌套循环的几种方法之间的差异,C++使用 OpenMP