I'm iterating through a map, that map value type is vector. I'm getting vectors in the map one by one and searching for a item using std::find() method.
for(BoundWaysMap::const_iterator iterator = boundWays.begin(); iterator != boundWays.end(); iterator++)
{
string wayId = iterator->first;
std::vector<string> nodesRefCollection = iterator->second;
if(std::find(nodesRefCollection.begin(), nodesRefCollection.end(), id)!=nodesRefCollection.end())
{
std::string cont = "|" + wayId;
legsFrame.append(cont);
legsCount ++;
isFound = true;
}
}
I want to get the index of the found item form the find method.
To find the indices of all occurrences of an element in a vector, we can repeatedly call the std::find_if function within a loop. The following example efficiently calls the std::find_if function, where the search for the next element begins at the previous match.
The most idiomatic way is to make your function take iterators: template<typename It> It::value_type maxsubarray(It begin, It end) { ... } and then use it like this: std::vector<int> nums(...); auto max = maxsubarray(begin(nums) + 2, end(nums));
How to find index of a given element in a Vector in C++. Given a vector V consisting of N integers and an element K, the task is to find the index of element K in the vector V. If the element does not exist in vector then print -1. The index of 54 is 2, hence output is 2.
The index of 54 is 2, hence output is 2. Recommended: Please try your approach on {IDE} first, before moving on to the solution. 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 .
We can access a vector element in different ways. Vectors are dynamic in nature, i.e. if we add an element to a vector, it increases its size by 1. But, we can access an element using the index of that element. In this post, we will learn how to access an element of a C++ vector. Each elements of a vector can be accessed by using its 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. Below is the implementation of the above approach :
std::find
returns an iterator to the found value, so you can get the index by using std::distance
on that iterator:
std::distance(nodesRefCollection.begin(), std::find(...));
You can keep the iterator returned by the find function like so:
std::vector<string>::iterator iter = std::find(nodesRefCollection.begin(), nodesRefCollection.end(), id);
if( iter != nodesRefCollection.end() )
{
int index = std::distance(nodesRefCollection.begin(), iter);
std::string cont = "|" + wayId;
legsFrame.append(cont);
legsCount ++;
isFound = true;
}
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