STL container template for this function?

Hi guys,

My teacher presented us with this function called lsearch. We are no longer allowed to use our own made up classes because we are moving towards STL templates such as vectors and deques. However, I'm having a hard time finding something similar that can replicate this function.

If anyone has any suggestions how I can use this as a deque or vector I'd greatly appreciate it.

Here is my lsearch function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <class DataType>
int Array<DataType>::lsearch(const DataType& data) const
{
	int result = -1; // break
	for (int i = 0; i < capacity; i++)
	{
		if (data == elements[i])
		{
			result = i;
			break;
		}
	}
	return result;
}
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' ;

}

http://ideone.com/lAU4gE
Last edited on
That is a linear search. If you would start your search from http://www.cplusplus.com/reference/algorithm/ then you might find something in finite number of steps.
Topic archived. No new replies allowed.