1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
template <class T> int getIndex( vector<T> v, T value )
{
for ( int i = 0; i < v.size(); i++ ) if ( v[i] == value ) return i;
return -1;
}
template <class T> int getAnotherIndex( vector<T> v, T value )
{
int i = find( v.begin(), v.end(), value ) - v.begin();
return ( i == v.size() ) ? -1 : i;
}
int getStringIndex( vector<string> v, const char *value )
{
for ( int i = 0; i < v.size(); i++ ) if ( v[i] == value ) return i;
return -1;
}
// Testing ...
int main()
{
// strings
vector <string> vec;
vec.push_back( "alpha" );
vec.push_back( "beta" );
vec.push_back( "gamma" );
vec.push_back( "delta" );
cout << "gamma --> " << getIndex( vec, string( "gamma" ) ) << endl; // should produce 2
cout << "Gamma --> " << getIndex( vec, string( "Gamma" ) ) << endl; // should produce -1 (not found)
cout << "gamma --> " << getAnotherIndex( vec, string( "gamma" ) ) << endl; // should produce 2
cout << "Gamma --> " << getAnotherIndex( vec, string( "Gamma" ) ) << endl; // should produce -1 (not found)
// character arrays
cout << "gamma --> " << getStringIndex( vec, "gamma" ) << endl; // should produce 2
cout << "Gamma --> " << getStringIndex( vec, "Gamma" ) << endl; // should produce -1 (not found)
// integers
vector <int> veci;
veci.push_back( 10 );
veci.push_back( 20 );
veci.push_back( 30 );
veci.push_back( 40 );
cout << "40 --> " << getIndex( veci, 40 ) << endl; // should produce 3
cout << "10 --> " << getIndex( veci, 10 ) << endl; // should produce 0
cout << "0 --> " << getIndex( veci, 0 ) << endl; // should produce -1 (not found)
}
|