-
locate index
It determines the location index of a number k.
Code:
#include <iostream>
using namespace std;
int main()
{
int a[1024], k, x, i, flag;
unsigned int n;
cin >> k >> n;
for ( i = 0; i < n; i++ )
{
cin >> x;
a[i] = x;
}
for ( i = 0; i < n; i++ )
{
if ( a[i] == k )
{
flag = i;
break;
}
else
flag = -1;
}
cout << flag <<endl;
}
If I use vector instead of array, is there a function that can do that?
-
std::find. To convert the iterator you get to an index, you have to subtract v.begin() from it.
-
How do I use this function can you give me an example?
-
Code:
std::vector<int> v;
fill(v);
std::vector<int>::iterator loc = std::find(v.begin(), v.end(), k);
std::vector<int>::size_type idx = loc == v.end() ? -1 : loc - v.begin();
-
You can find a brief description of how to use std::find, along with two examples, at cppreference.com's entry on std::find. Notice that the second example actually demonstrates using std::find with an array.
If you are using an associative container like std::map, on the other hand, then it would be better to use the find function provided by that container as it would be more efficient.
-