我想寫一個從STL容器返回一對值的函數。STL模板函數返回一對
template <typename T>
std::pair<typename T::value_type,typename T::value_type> getMinMax(T &container) {
auto min = *(container.begin());
auto max = *(container.begin());
for (auto it : container) {
if (min > (*it)) {
min = (*it);
}
if (max < (*it)) {
max = (*it);
}
}
return std::make_pair(min, max);
};
int main() {
std::vector<int> c{1, 2, 3, 4, 5};
auto p = getMinMax(c);
std::cout << "min: " << p.first << " max: " << p.second << "\n";
}
我得到一個錯誤:
error: indirection requires pointer operand ('int' invalid) if (min > (*it)) {
我不知道該如何面對這一切。
除了這個錯誤,是否有更好的方法來實現所需的行爲?
http://en.cppreference.com/w/cpp/algorithm/minmax – Justin
*是否有更好的方法來實現所需的行爲?*。是的,['std :: minmax_element'](http://en.cppreference.com/w/cpp/algorithm/minmax_element) – NathanOliver
@ user1211030在這個代碼片段中用於(auto it:容器){if(min>( * it)){分鐘=(* it); }它不是一個迭代器或指針。它具有值類型。所以刪除解引用。 –