Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find an element position in std::vector?

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?

like image 294
sharptooth Avatar asked Sep 15 '09 05:09

sharptooth


People also ask

How do you get the position of an element in a vector?

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.

How do you find the position of the maximum element in a vector?

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.


2 Answers

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 } 
like image 191
Naveen Avatar answered Sep 18 '22 16:09

Naveen


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(); 
like image 45
larsmoa Avatar answered Sep 17 '22 16:09

larsmoa