Recursive linear search c++

Question:

I wanted to do a linear recursive search using vector and iterators, here's the code:

long int busca_sr(std::vector<long int> &amostra, const long int &key){
    auto first = amostra.begin();
    auto last = amostra.end();
    if (last == first-1){
        return -1;
    }
    else if(*last == key){
        return 1;
    }
    else{ 
        --last;
        std::vector <long int> auxi1 (first, last);
        return busca_sr(auxi1, key); 

    }

The problem is that when I run this function my pc crashes, I suspect that the error is in the stop condition of my recursion, because when the last is equal to the first, the auxiliary vector at the bottom will not be allocated, I would like a way to insert a stop condition without having to change the function signature!

Answer:

Since it's a linear search, I think it's more natural for you to start scanning from the first element and go through the beginning iterator by 1 instead of starting with the last element.

Another point that was wrong was the stopping criterion: the condition if(last == first-1) always gives an exception, as you are trying to read an index before the first position. To see if the iterator has reached the end of the vector, just check v.begin() == v.end() .

long int busca_sr(std::vector<long int> &amostra, const long int &key) {
    std::vector<long int>::iterator first = amostra.begin();
    std::vector<long int>::iterator last = amostra.end();

    if (last == first) {
        return -1;
    }
    else if (*first == key) {
        return 1;
    }
    else {
        std::vector <long int> auxi1(++first, last);
        return busca_sr(auxi1, key);
    }
}
Scroll to Top