Existe uma maneira de encontrar o inverso de um iterador para o primeiro elemento de um std::map menos do que uma determinada chave?

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

Pergunta

Me deparei com o seguinte trecho de código em C++ (eu ainda não estou em 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;
}

Em particular, eu não gosto do uso de --itr no final, nem a comparação do itr para begin(), ambos se sentir mal para mim.

Eu estou querendo saber se existe uma forma com STL para fazer algum tipo de pesquisa que seria return end() (ou rend()) se não encontrado, e do contrário, para retornar o último elemento que é menor do que ou igual a value então o código ficaria assim:

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

Em um sentido, eu quero um reverse_lower_bound() que retorna um iterador reverso para o último elemento que não é maior do que o value ou se nenhum pode ser encontrado rend().

Foi útil?

Solução

Com base no Xeo do comentário, acho que esta é a resposta:

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

Eu aprendi essa nova coisa:

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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top