簡體   English   中英

如何實現一個函數的頭部,使得下面的代碼可以工作?

[英]How to implement the header of a function such that the following code works?

vector<int> v1{4, 2, 1, 6, 3, -4};
assert(fct<int>(v1) == 6);
vector<int> v2;
try {
        fct<int>(v2);
        assert(false);
}
catch (exception& exc) {
assert(true);
}
vector<double> v3{2, 10.5, 6.33, -100, 9, 1.212};
assert(fct<double>(v3) == 10.5);

vector<string> v4{"y", "q", "a", "m"};
assert(fct<string>(v4) == "y");

我知道 fct 函數應該返回向量的最大值,但我無法理解函數的標題應該是什么樣子。

我猜你的意思是函數聲明(不是“標題”),所以它應該是這樣的:

template<typename T>
T fct(const std::vector<T>& v);

PS:

  1. 您不應將該函數命名為“fct”,而應為其指定一個適當的名稱,例如“max_element”或其他名稱(或使用標准庫提供的std::max_element函數)

  2. 不要使用using namespace std; 請參閱: 為什么是“使用命名空間 std;” 被認為是不好的做法

  3. 如果您沒有綁定到某些較舊的 C++ 標准(或編譯器),則 可以在調用函數時省略模板參數: assert(fct(v1) == 6);

暫無
暫無

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

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