C'è un modo per trovare un iteratore inversa per il primo elemento in un STD :: Mappa meno di una determinata chiave?

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

Domanda

Mi sono imbattuto nel seguente snippet di codice in C ++ (non sono ancora su 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;
}
.

In particolare, non mi piace l'uso del --itr alla fine né il confronto del itr a begin(), entrambi si sentono sbagliati per me.

Mi chiedo se c'è un modo con STL per fare una specie di ricerca che ritornerebbe () (o rendendo ()) se non trovato e in caso contrario a restituire l'ultimo elemento che è inferiore o uguale alvalue Quindi il codice sarebbe più simile a questo:

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

In un certo senso, voglio un reverse_lower_bound () che restituisce un iteratore inverso all'ultimo elemento che non è maggiore del value o se nessuno può essere trovato Rend ().

È stato utile?

Soluzione

Basato sul commento di XEO, penso che questa sia la risposta:

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

Ho imparato questa nuova cosa:

When an iterator is reversed, the reversed version does not point to the same
element in the range, but to the one preceding it.
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top