For example, I have an array with elements 1,7,9,23,34,47,67,89,123,234,345,567. I need to know the position of 123.
Asked
Active
Viewed 1.9k times
7
-
[`std::find`](http://en.cppreference.com/w/cpp/algorithm/find) Ought to work just fine. You can subtract `std::begin(array)` to get an (numerical) index rather than an iterator if that's what you need. – Xirema Nov 17 '16 at 17:55
-
Have you tried anything? please provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – George Nov 17 '16 at 17:57
-
@Xirema with std::find you have the same problem. The function returns that iterator, not the position. So you still have to do the calculation in User_Targaryen's answer. – Elliott Feb 08 '20 at 08:20
-
@George, I think that the OP provided a complete minimal example (it doesn't look like they've edited it since your comment either). – Elliott Feb 08 '20 at 08:22
-
@Elliott All I can see is "For example, I have an array with elements 1,7,9,23,34,47,67,89,123,234,345,567. I need to know the position of 123.". The sequence bit doesn't count, it needs to be a code example, a C++ code example really from the tag. – George Feb 08 '20 at 10:13
-
Together with the title of the question, it seems pretty explicit: std::lower_bound on an array to get the index instead of the element. Sure, the OP's question could be a bit better, but not enough to require revision. – Elliott Feb 08 '20 at 14:31
1 Answers
8
Declare and initialize the array with the elements. Then create a vector
of ints. Use upper_bound()
on the vector
. Here is an example:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int arr[] = {1,7,9,23,34,47,67,89,123,234,345,567};
int len = sizeof(arr)/sizeof(arr[0]);
vector<int> v(arr,arr+len);
vector<int>::iterator upper;
upper = upper_bound(v.begin(), v.end(), 123);
cout<<(upper-v.begin())<<endl; // Output: 9
return 0;
}
Hope it helps!!

User_Targaryen
- 4,125
- 4
- 30
- 51
-
7You can use `std::upper_bound` and `std::lower_bound` directly on the array. There's no need for that vector. – Pete Becker Nov 17 '16 at 18:46
-
2`std::upper` returns the first value **greater** than the sought one. If, for instance, you had sought for value 122 you would still get position 9 (or rather, 8), even though the value you looked for wasn't found. – marcbf Nov 28 '18 at 13:46
-
@Elliott No, it's actually as I wrote it. Have a look: https://en.cppreference.com/w/cpp/algorithm/upper_bound You're thinking of `std::lower_bound` which returns an iterator to either the value you're looking for or the one preceding it. For both `std::lower_bound` and `std::upper_bound` `end()` is returned if no suitable value could be found. – marcbf Feb 10 '20 at 06:32