簡體   English   中英

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::arraystd::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忠實std::endl 您是否知道它會寫一個'\\n' 並刷新流 很多人沒有意識到它做兩件事,這使得您的代碼的意圖不太清楚。 當我閱讀它時,我不知道寫它的人是否真的想刷新流,或者只是不知道std::endl 我更喜歡只用

std::cout << '\n';

,或者如果您確實確實想手動刷新流(不太可能),請對其進行明確說明:

std::cout << '\n' << std::flush;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM