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:container){ if(min>( * it)){ min =(* it); }イテレータまたはポインタではありません。それは値の型を持っています。したがって、逆参照を削除してください。 –