¿Hay alguna manera de encontrar un iterador inverso para el primer elemento en un std::map menor que una clave determinada?

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

Pregunta

Me encontré con el siguiente fragmento de código en C++ (todavía no estoy en 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;
}

En particular, no me gusta el uso de --itr al final ni la comparación de itr a begin(), ambos me parecen mal.

Me pregunto si hay una manera con STL de hacer algún tipo de búsqueda que devolvería end() (o rend()) si no se encuentra y, de lo contrario, devolvería el último elemento que es menor o igual que el value entonces el código se parecería más a esto:

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;
}

En cierto sentido, quiero un Reverse_lower_bound() que devuelva un iterador inverso al último elemento que no sea mayor que el value o si no se puede encontrar ninguno, render().

¿Fue útil?

Solución

Según el comentario de Xeo, creo que esta es la respuesta:

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;
}

Aprendí esta cosa nueva:

When an iterator is reversed, the reversed version does not point to the same
element in the range, but to the one preceding it.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top