我想写一个从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); }它不是一个迭代器或指针。它具有值类型。所以删除解引用。 –