0

In a previous post, the use of std::upper_bound() and std::lower_bound() were discussed. However, the question focused on getting the element, and in this post, I am focused on getting the index of the element. The particular problem I have is as follows. I have a cumulative distribution of a random variable (let's say shirt color).

  • white : 0.5
  • black : 0.6
  • green : 0.8
  • blue : 1.0

I will generate a random number uniformly between [0, 1.0] and then need to map that back to the cumulative probability. For example, if the random number is in [0, 0.5), then "white", if the random number number is in [0.5, 0.6) then "black", and so on.

I might store my probabilities in std::vector<double>, but std::upper_bound() and std::lower_bound() will return an iterator to access the element, not the index. That is fine, but then I will need perhaps a std::map<double, std::string> to map the double back to the string value.

In the context of what I am trying to achieve, is there a way to get the index of an element like with Python's bisect method?

Jane Wayne
  • 8,205
  • 17
  • 75
  • 120

0 Answers0