std::find() 不能用 gcc 编译

std::find() can't compile with gcc

本文关键字:gcc 编译 不能 find std      更新时间:2023-10-16
#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; 。看这里或这里。它清楚地表明您正在尝试使用标准库find,而不是其他东西。

尝试打印之前,最好先检查您的find是否确实找到了某些内容。如果您尝试find不存在的值,则打印它会导致未定义的行为,这是一件坏事。

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;