指定されたキーより小さい std::map の最初の要素の逆反復子を見つける方法はありますか?

StackOverflow https://stackoverflow.com/questions/9503489

質問

C++ で次のコード スニペットを見つけました (私はまだ C++11 を使用していません)。

int test(std::map<int, size_t> &threshold, const int value) {
  std::map<int, size_t>::const_iterator itr = threshold.upper_bound(value);

  if (threshold.begin() == itr) {
    return -1;
  }
  return return (--itr)->second;
}

特に、次のような使い方は好きではありません。 --itr 最後に比較することもできません itrbegin(), 、私にはどちらも間違っていると感じます。

STL で、見つからない場合は end() (または rend()) を返し、見つからない場合は以下の最後の要素を返す、ある種の検索を実行する方法があるかどうか疑問に思っています。 value したがって、コードは次のようになります。

int test(std::map<int, size_t> &threshold, const int value) {
  std::map<int, size_t>::const_reverse_iterator itr = threshold.WhatGoesHere(value);

  if (threshold.rend() == itr) {
    return -1;
  }
  return return itr->second;
}

ある意味、私は、以下の最後の要素への逆反復子を返す reverse_ lower_bound() が必要です。 value 何も見つからない場合は、 rend() を実行します。

役に立ちましたか?

解決

Xeo のコメントに基づくと、これが答えだと思います。

int test(std::map<int, size_t> &threshold, const int value) {
  std::map<int, size_t>::const_reverse_iterator
    last_element_not_greater_than(threshold.upper_bound(value));

  if (threshold.rend() == last_element_not_greater_than) {
    return -1;
  }
  return return last_element_not_greater_than->second;
}

私は次のような新しいことを学びました:

When an iterator is reversed, the reversed version does not point to the same
element in the range, but to the one preceding it.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top