find() Function in C++

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.

  1. /* 
  2.  * C++ Program to Create vector of Strings and Find an Element using iterators
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <string>
  7. #include <algorithm>
  8.  
  9. int main()
  10. {
  11.     std::vector<std::string> StringVector;
  12.     std::vector<std::string>::iterator iter;
  13.     std::string lang;
  14.  
  15.     StringVector.push_back("Python");
  16.     StringVector.push_back("Java");
  17.     StringVector.push_back("Haskell");
  18.     StringVector.push_back("C++");
  19.     StringVector.push_back("Ruby");
  20.     StringVector.push_back("JavaScript");
  21.     std::cout << "Which language do you want to find? " ;
  22.     std::cin >> lang;
  23.     iter = find(StringVector.begin(), StringVector.end(), lang);
  24.     // find() returns StringVector.end() if not found
  25.     if(iter != StringVector.end())
  26.     {
  27.         std::cout << *iter << " is on position "
  28.                   << (iter - StringVector.begin() + 1);
  29.     }
  30.     else
  31.     {
  32.         std::cout << lang << " not found";
  33.     }
  34.     std::cout << std::endl;
  35. }

$ 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
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.