I need to find an element position in an std::vector to use it for referencing an element in another vector:
int find( const vector<type>& where, int searchParameter ) { for( int i = 0; i < where.size(); i++ ) { if( conditionMet( where[i], searchParameter ) ) { return i; } } return -1; } // caller: const int position = find( firstVector, parameter ); if( position != -1 ) { doAction( secondVector[position] ); }
however vector::size()
returns size_t
which corresponds to an unsigned
integral type that can't directly store -1
. How do I signal that the element is not found in a vector when using size_t
instead of int
as an index?
find(): Used to find the position of element in the vector. Subtract from the iterator returned from the find function, the base iterator of the vector . Finally return the index returned by the subtraction.
To find the largest or smallest element stored in a vector, you can use the methods std::max_element and std::min_element , respectively. These methods are defined in <algorithm> header. If several elements are equivalent to the greatest (smallest) element, the methods return the iterator to the first such element.
Take a look at the answers provided for this question: Invalid value for size_t?. Also you can use std::find_if with std::distance to get the index.
std::vector<type>::iterator iter = std::find_if(vec.begin(), vec.end(), comparisonFunc); size_t index = std::distance(vec.begin(), iter); if(index == vec.size()) { //invalid }
First of all, do you really need to store indices like this? Have you looked into std::map, enabling you to store key => value pairs?
Secondly, if you used iterators instead, you would be able to return std::vector.end() to indicate an invalid result. To convert an iterator to an index you simply use
size_t i = it - myvector.begin();
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