Vincent
Vincent

Reputation: 60381

Index of first element > to a number in a vector with STL::algorithm?

I have a sorted std::vector<unsigned long long int> myvector (and all values are different).

What is the shortest way to find the value of the first index size_t idx (not an iterator) of myvector strictly > to MAX_UI32 = 4294967295U.

For example :

[1, 34, 83495, 4294967295, 4294967296, 104000000000] -> idx = 4
[1, 34, 83495, 923834, 912834823, 4294967295] -> idx = 6 (= size of myvector)

How to achieve this in one line of code ?

Thank you very much.

Upvotes: 0

Views: 656

Answers (3)

Bojan Komazec
Bojan Komazec

Reputation: 9526

Just to add that you can use and std::find_if but in that case you need to write a predicate function:

bool IsBigger(unsigned long long int ull) {
  return (ull > MAX_UI32);
}

std::vector<unsigned long long int>::iterator it = std::find_if(v.begin(), v.end(), IsBigger);
size_t index = std::distance(v.begin(), it);

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477060

A combination of upper_bound and distance should do the trick:

#include <algorithm>
#include <iterator>
#include <vector>

std::vector<unsigned long long int> v;

// ...

return std::distance(v.begin(),
                     std::upper_bound(v.begin(), v.end(), MAX_UI32));

If there is no such element, upper_bound returns v.end(), so your result will equal v.size().

Upvotes: 3

Ben Hocking
Ben Hocking

Reputation: 8072

Use upper_bound in algorithm. See: http://www.cplusplus.com/reference/algorithm/upper_bound/

Upvotes: 2

Related Questions