gpt4 book ai didi

c++ - std::find() 不能用 gcc 编译

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:13 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com