Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for an element in a vector?

Tags:

c++

find

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"?

like image 996
Prasanth Madhavan Avatar asked Nov 22 '10 07:11

Prasanth Madhavan


People also ask

How do you find if an element exists in a vector?

So, to check if an element exist in vector or not, we can pass the start & end iterators of vector as initial two arguments and as the third argument pass the value that we need to check. If element exists in the vector, then it will return the iterator pointing to that element.

Can you do binary search on a vector?

Do note that a binary search only works on a sorted data set. If the user enters non sorted data then you need to sort the vector before you can run a binary search on it.

How do you access the elements of a vector by index?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.

How do you find the first occurence of a element in a vector C++?

C++ provides the functionality to find an element in the given range of elements in a vector. This is done by the find() function which basically returns an iterator to the first element in the range of vector elements [first, last) on comparing the elements equals to the val (value to be searched).


2 Answers

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;
}
like image 178
kennytm Avatar answered Sep 16 '22 22:09

kennytm


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.

like image 28
逆さま Avatar answered Sep 20 '22 22:09

逆さま