Nov 6, 2012 at 9:13pm
how can i find the index of a certain number in a vector?
Last edited on Nov 7, 2012 at 8:44am
Nov 6, 2012 at 9:18pm
There is special standard algorithm that has name
std::find
For example
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::cout << std::distance( v.begin(), std::find( v.begin(), v.end(), 5 ) ) << std::endl;
Here is a compiled example
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::cout << std::distance( v.begin(), std::find( v.begin(), v.end(), 5 ) ) << std::endl;
}
|
The output is
4
Last edited on Nov 6, 2012 at 9:23pm
Nov 7, 2012 at 1:37pm
It will give you 0 because 5 is the first element of your vector after sorting.