Reputation: 543
I'm trying to implement a function to find a vector in a 2D vector. What i have wrote is:
vector<vector<int> > result;
vector<int> line;
bool isPresent = find(result.begin(), result.end(), line)
However, this gives an error that
"Line 11: cannot convert ‘__gnu_cxx::__normal_iterator*, std::vector > >’ to ‘bool’ in initialization"
I searched many forums but couldn't find the right answer. What is the best way to do that?
Thanks, Shawn
Upvotes: 4
Views: 10649
Reputation: 48447
InputIterator std::find(InputIterator first, InputIterator last, const T& val)
Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.
Instead use:
bool isPresent = std::find(result.begin(), result.end(), line) != result.end();
// ^^^^^^^^^^^^^^^
or:
bool isPresent = std::any_of(result.begin(), result.end(),
[&line](const std::vector<int>& x)
{ return x == line; });
Upvotes: 9
Reputation: 4432
Change by:
bool isPresent = (find(result.begin(), result.end(), line) != result.end());
Or Better if C++11 allowed:
bool isPresent = (find(cbegin(result), cend(result), line) != cend(result));
The method std::find
of the containers return an iterator
of the element that match or the range end
(last in the signature method) provided if the element is not present.
template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);
Upvotes: 3
Reputation: 1
Change your code to
bool isPresent = find(result.begin(), result.end(), line) != result.end();
That should work as you want it. As mentioned std::find()
returns a vector<vector<int> >::iterator
, not a bool
.
Upvotes: 1
Reputation: 17411
My first guess would be find
returns the iterator where it found the item you asked it to find and not a boolean.
It should look like this:
vector<vector<int> > result;
vector<int> line;
vector< vector<int> >::iterator it = find(result.begin(), result.end(), line);
bool isPresent = ( it != result.end() );
Upvotes: 1