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"?
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.
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.
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.
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).
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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With