c++ - std::find() 无法使用 gcc 编译

标签 c++

#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::arraystd::find ,而不是 using namespace std; 。请参阅herehere 。它清楚地表明您正在尝试使用标准库 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/

相关文章:

c++ - 作为 C++11 属性参数的变量

c# - 如何将 native C/C++ *.dll 连接到 IIS 中托管的 WCF C#?

python - 如何在Python中实现泛型? Java 或 C++ 之类的东西提供

C++三元运算符,有什么区别?

c++ - epoll数据结构中同时使用void *ptr和int fd

c++ - 程序只有在我在 Visual Studio 中运行时才会执行

c++ - std::pair 提示类型不完整

c++ - 嵌套的 if 语句和 "&&"运算符

c++ - 查找数组中数组元素的重复出现?

c++ - vector 迭代器不兼容(段错误)