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

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.