c++algorithmvectorrange-based-loop

Find element in a vector with previous and next element equal to 0


I want to go through a given vector of integers and find an integer which the value of the next and previous integer are 0.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> sample = { 0,3,0 };
    for (int i : sample)
    {
        if (sample[i - 1] == sample[i + 1] == 0)
        {
            cout << "hello";
        }
    }
}

However, I keep getting a "vector subscript out of range" error. I think it's because when i is 0, sample[-1] doesn't exist, same with i = 2.

Is there an easy fix for it?


Solution

  • This range based for loop

    for (int i : sample)
    {
        if (sample[i - 1] == sample[i + 1] == 0)
        {
            cout << "hello";
        }
    }
    

    does not make a sense because there are used values of the vector as indices to the vector.

    The range based for loop is not suitable for such a task.

    You can use for example the standard algorithm std::adjacent_find.

    Here is a demonstration program.

    #include <iostream>
    #include <vector>
    #include <iterator>
    #include <algorithm>
    
    int main() 
    {
        std::vector<int> v = { 0, 1, 0, 2, 0, 3, 0 };
        
        auto condition = []( const auto &a, const auto &b )
        {
            return a != 0 && b == 0;
        };
        
        if ( not v.empty() )
        {
            for ( auto current = std::next( std::begin( v ) ), last = std::end( v ); 
              ( current = std::adjacent_find( current, std::end( v ), condition ) ) != last;
              std::advance( current, 2 ) )
            {
                if ( *std::prev( current ) == 0 )
                {
                    std::cout << *prev( current ) << ", " 
                              << *current << ", " 
                              << *std::next( current ) << '\n';
                }
            }
        }       
        
        return 0;
    }
    

    The program output is

    0, 1, 0
    0, 2, 0
    0, 3, 0