0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++ vector の最大値・最小値を取得する方法

Posted at

AtCoder に挑戦した際,ベクターの要素から最小値を求める方法を忘れていたので備忘録として残しておきます.

ベクターの最大値・最小値

ベクターの最大値・最小値はmax_element, min_element 関数を用いて取得できます.
max((last - first) - 1, 0) 回の比較を行うため,計算量は O(n)になります.

  • ベクターの要素が数値(int型,float型などの時)の時
# 最大値の取得
std::vector<int> v = {3, 1, 4};
auto max_iterator = std::max_element(v.begin(), b.end());
int max = *max_iterator;

# 最小値の取得
std::vector<int> v = {3, 1, 4};
auto mix_iterator = std::mix_element(v.begin(), b.end());
int mix = *mix_iterator;
  • ベクターの要素がペアの時
std::vector<std::pair<int, int>> v = {{0, 3}, {1, 1}, {2, 4}};

# 一つ目の要素に関して最大値・最小値を求めたい場合
auto max_iterator = std::max_element(v.begin(), b.end());
std::cout << max_iterator->first << std::endl;
std::cout << max_iterator->second << std::endl;

# 二つ目の要素に関して最大値・最小値を求めたい場合
auto max_iterator = std::max_element(v.begin(), v.end(), [](const auto& a, const auto& b) {
		return a.second < b.second;
});
std::cout << max_iterator->first << std::endl;
std::cout << max_iterator->second << std::endl;

参考サイト

備考

不備などございましたら,教えていただけると幸いです.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?