This C++ program creates a vector and uses find() to search for an element. The program creates a vector and uses find() function from algorithm library. The iterator to the beginning and end of the vector is passed as parameter to the function find() and also the key that is to be found.
Here is the source code of the C++ program creates a vector uses find() to search for an element. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Create vector of Strings and Find an Element using iterators
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
std::vector<std::string> StringVector;
std::vector<std::string>::iterator iter;
std::string lang;
StringVector.push_back("Python");
StringVector.push_back("Java");
StringVector.push_back("Haskell");
StringVector.push_back("C++");
StringVector.push_back("Ruby");
StringVector.push_back("JavaScript");
std::cout << "Which language do you want to find? " ;
std::cin >> lang;
iter = find(StringVector.begin(), StringVector.end(), lang);
// find() returns StringVector.end() if not found
if(iter != StringVector.end())
{
std::cout << *iter << " is on position "
<< (iter - StringVector.begin() + 1);
}
else
{
std::cout << lang << " not found";
}
std::cout << std::endl;
}
$ a.out Which language do you want to find? Python Python is on position 1 $ a.out Which language do you want to find? Lisp Lisp not found
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Check Computer Science Books
- Apply for Computer Science Internship
- Apply for C++ Internship
- Practice Programming MCQs
- Check C++ Books