-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchUsingGenerate.cpp
57 lines (44 loc) · 1.31 KB
/
SearchUsingGenerate.cpp
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
/**
* \file SearchUsingGenerate.cpp
* \brief
*
* \todo
*/
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
/*
* Generic function to find if an element of any type exists in list
*/
template<typename T>
bool contains(std::list<T> & listOfElements, const T & element)
{
// Find the iterator if element in list
auto it = std::find(listOfElements.begin(), listOfElements.end(), element);
//return if iterator points to end or not. It points to end then it means element
// does not exists in list
return it != listOfElements.end();
}
int main()
{
std::list<std::string> listOfStrs =
{ "is", "of", "the", "Hi", "Hello", "from" };
/* Use the same generic function with list of Strings */
// Check if an element exists in list
bool result = contains(listOfStrs, std::string("is"));
std::cout << result << std::endl;
// Check if an element exists in list
result = contains(listOfStrs, std::string("day"));
std::cout << result << std::endl;
/* Use the same generic function with list of int */
// List of ints
std::list<int> listOfNum =
{ 1, 2, 3, 4, 6, 7, 8 };
// Check if an element exists in list
result = contains(listOfNum, 3);
std::cout << result << std::endl;
// Check if an element exists in list
result = contains(listOfNum, 3);
std::cout << result << std::endl;
}