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
|
// return position [ 0, (N-1) ] if found
// return invalid position N if not found
template < typename SEQUENCE_CONTAINER >
typename SEQUENCE_CONTAINER::size_type lsearch( const SEQUENCE_CONTAINER& seq,
const typename SEQUENCE_CONTAINER::value_type& data )
{
typename SEQUENCE_CONTAINER::size_type pos = 0 ;
for( const auto& value : seq )
{
if( data == value ) return pos ;
else ++pos ;
}
return seq.size() ;
}
#include <vector>
#include <list>
#include <string>
#include <iostream>
int main()
{
std::vector<int> vec { 53, 65, 64, 74, 74, 74, 32, 17, 23, 29, 86 } ;
auto f = lsearch( vec, 17 ) ;
if( f != vec.size() ) std::cout << "found at position " << f << '\n' ;
std::list<std::string> lst { "abc", "def", "ghi", "jkl", "mnop", "qrst", "uvwxyz" } ;
std::cout << lsearch( lst, "mnop" ) << '\n' ;
std::string phrase = "STL container template for this function" ;
std::cout << lsearch( phrase, 'L' ) << '\n' ;
}
|