#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;
。看到这里或这里。很明显,您正在尝试使用标准库find
,而不是其他库。
find
在尝试打印之前,最好检查一下您是否确实找到了某些东西。如果尝试find
使用不存在的值,则打印该值将导致Undefined Behavior,这是一件坏事。
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
。您知道它写入a'\n'
并刷新流吗?许多人没有意识到它可以做两件事,这使得您的代码意图不太清楚。当我阅读它时,我不知道写它的人是否真的想冲洗流,或者只是不知道要冲洗std::endl
。我更喜欢只用
std::cout << '\n';
,或者如果您确实确实想手动刷新流(不太可能),请对其进行明确说明:
std::cout << '\n' << std::flush;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句