简体   繁体   中英

Finding index in std::vector

I am new to C++. I am trying to find the index of the element if there is a subset in the vector.

I have my code below.. Please help me with the solution.

#include <iostream>
#include <vector>
#include <algorithm>
 
int main()
{
    std::vector<uint8_t> v = { 1,2,3,4,0,6,7,8,4,5,6 };
    int key = 4;
    std::vector<uint8_t>::iterator itr = std::find(v.begin(), v.end(), key);
 
    if (itr != v.cend()) {
        uint8_t index = std::distance(v.begin(), itr);
        if ((++index == 5) && (++index == 6))
            std::cout << "Element present at index " << index-2;
        else
            continue;
    }
    else {
        std::cout << "Element not found";
    }
 
    return 0;
} 

In the above code, I want to print the index of the element '4' if 4,5,6 are consecutive elements.

Output: 8

You must replace your first if by a while with the same test, replace both of your ++index by *(++itr) , not subtract 2 to index before printing it, and replace your last else by if(itr == v.cend()) to get the output you want.

Note that this code doesn't work anymore if you change the expected elements to find from {4,5,6} to {4,4,6} for example, so I would suggest you to change the general approach of your problem if you want to generalize it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM