Q:

How to search for an element in a vector?

i have a code like this....
std::vector<string>::iterator p;
p =  find(v.begin(),v.end(),"asdasda"); 
cout << *p << endl;

if "asdasda" is not a part  of the vector, p points to some garbage and cout gives a seg fault. what should be the if statement that would make the cout execute onlyif "asdasda" was found?
and also the position of "asdasda" in v.. like if we had earlier declared v[3] as "asdasda",
then how can i know from the find that v[3] is "asdasda"?

A:

p doesn't point to "garbage", it simply becomes v.end() when the content is not found.
if (p != v.end()) {
   std::cout << "v[" << (p - v.begin()) << "] = ";
   std::cout << *p << std::endl;
}

A:

If std::find doesn't find anything, the iterator is set to v.end() in this case.
if ( p != v.end() )
{
    // iterator is good
}

Also note the general case of std::find.
Here's a typical definition of it:
namespace std {
  template <class InputIterator, class T>
  InputIterator find(InputIterator start, 
                     InputIterator finish,
                     const T& value);
}

In case std::find fails, it will return the finish iterator because the search is [start, finish) and includes start but excludes finish.

