c++比较std::array和只有一个变量的std::array



我知道我的标题很难理解我的意思,但我是c++的新手,所以我希望你能理解我的问题,我试图用一个例子向你展示这个问题:

#include<conio.h>
#include<iostream>
#include <array>
using namespace std;
int main() {
std::array<short int, 3> testarr = {1, 2, 3};
if(testarr == {1, 2, 3}) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}

抛出编译错误:

||=== Build file: Debug in x(compiler: GNU GCC Compiler) ===|
C:UsersxProgrammingC++xtest.cpp||In function 'int main()':|
C:UsersxProgrammingC++xtest.cpp|11|error: expected primary-expression before '{' token|
C:UsersxProgrammingC++xtest.cpp|11|error: expected ')' before '{' token|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

如果我想将std::数组与另一个数组进行比较,并且只使用一次,我是否必须创建一个新变量?

我自己想出来的。可以通过使用std::array类来实现,而不需要创建一个新变量:

#include<conio.h>
#include<iostream>
#include <array>
using namespace std;
int main() {
std::array<short int, 3> testarr = {1, 2, 3};
if(testarr == std::array<short int, 3>{1, 2, 3}) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}

最新更新