#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int, 5> a = {1,2,3,4,5};
auto it = find(a.cbegin(), a.cend(), 3);
cout << *it << endl;
return 0;
}
程序使用 VS 2015 运行良好,但使用 gcc 编译失败。代码有错吗? 错误信息是:
error: no matching function for call to ‘find(std::array<int, 5ul>::const_iterator, std::array<int, 5ul>::const_iterator, int)’
最佳答案
你需要
#include <algorithm>
这就是 std::find
生活。看来使用 MSVC 你可以通过 <iostream>
中的一些传递包含来获得它或<array>
.
我还建议完全限定标准库组件的名称,例如 std::array
和std::find
,而不是 using namespace std;
。请参阅here或here 。它清楚地表明您正在尝试使用标准库 find
,而不是其他东西。
最好检查您的 find
在尝试打印之前实际上发现了一些东西。如果您尝试 find
一个不存在的值,然后打印它会导致 Undefined Behaviour ,这是一件坏事。
auto it = std::find(a.cbegin(), a.cend(), 3);
if ( a.cend() == it ) {
std::cout << "Couldn't find value!\n";
return 1;
}
std::cout << *it << '\n';
return 0;
我也不太喜欢 std::endl
。你知道吗,它写着 '\n'
并刷新流?很多人没有意识到它做了两件事,这使得代码的意图变得不太清楚。当我读到它时,我不知道写它的人是否真的想要刷新流,或者只是不知道 std::endl
这样做。我更喜欢只使用
std::cout << '\n';
,或者如果您确实想手动刷新流(不太可能),请明确说明:
std::cout << '\n' << std::flush;
关于c++ - std::find() 无法使用 gcc 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34412104/