هل هناك طريقة للعثور على عكس مكرر لأول عنصر في std::خريطة أقل من معين المفتاح ؟

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 في النهاية ولا مقارنة من itr إلى begin(), كلاهما يشعر الخاطئ لي.

أنا أتساءل عما إذا كان هناك طريقة مع المحكمة الخاصة بلبنان إلى القيام ببعض النوع من البحث الذي سيعود في نهاية() (أو تمزق()) إذا لم يتم العثور على خلاف ذلك العودة إلى العنصر الأخير هو أقل من أو يساوي 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 أو إذا كان لا يمكن العثور على رند().

هل كانت مفيدة؟

المحلول

على أساس 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