简体   繁体   中英

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");

I know that the fct function should return the maximum of the vector but I can't wrap my head on how the header of the function should look like.

I guess you meant the function declaration (not "header"), so that's what it should look like:

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

PS:

  1. You should not name that function "fct", but give it an appropriate name, like "max_element" or something (or use the function std::max_element provided by the standard lib)

  2. Don't use using namespace std; see: why is 'using namespace std;' considered bad practice

  3. If you're not bound to some older C++ standard (or compiler), you can omit the template parameter when calling your function: assert(fct(v1) == 6);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM