주어진 키보다 작은 std::map의 첫 번째 요소에 대한 역방향 반복자를 찾는 방법이 있습니까?
-
14-11-2019 - |
문제
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
결국에는 비교도 안 되고 itr
에게 begin()
, 둘 다 나에게 잘못되었다고 느낍니다.
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.
. 제휴하지 않습니다 StackOverflow