std::find() 不能用 gcc 编译
std::find() can't compile with gcc
#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
不存在的值,则打印它会导致未定义的行为,这是一件坏事。
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;
相关文章:
- 为什么 gcc 编译这个而 msvc 没有
- 错误:使用 clang 没有可行的重载,使用 GCC 编译
- 带有自动参数的函数使用 GCC 编译,但不使用 Visual C++ 编译
- 使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
- Steam 回调在 Linux / GCC 编译期间触发警告
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 如何使用 GCC 编译指示启用选项 '-Werror'?
- 如何实现使用 gcc-4.4 编译的大向量初始化?
- 关于这个在 Linux 上使用 gcc 编译的程序中的 vtable,nm 告诉我什么?
- 使用 TDM GCC 5.1.0 编译 PDCurses36 时出错
- 为什么这段代码无法使用 gcc 4.8.5 编译,而使用 clang 编译正常
- 使用 std::addressof 时出现 GCC 7 编译错误
- 在类模板上使用 arm gcc 编译期间的隔离错误
- 使用 GCC 编译C++时如何包含 C11 标头?
- 类数据成员指针的非类型模板参数包无法使用 gcc 编译
- 是否可以使用 GCC 编译具有特定编译器标志的代码文件的一部分?
- 将 cctype 函数分配给 std::function,gcc 编译错误
- GCC 编译时出现警告:未知转义序列:"\040"
- 为什么以下代码不使用GCC编译,而是用Clang编译罚款
- GCC编译器,为较低版本的GCC编译应用程序