Home > front end >  C : Return the iterator pointing to element equally to the target
C : Return the iterator pointing to element equally to the target

Time:10-13

I want to find out the iterator pointing to an element equal to the target.

The following code does not work for me, what's wrong with this code?

#include <iostream>
#include <vector>

template <typename T>
typename std::vector<T>::iterator find_it(std::vector<T> vec, const int target){
    std::vector<T>::iterator it = vec.begin();
    while(it != vec.end() ){
        if(*it == target) return it;
        it  ;
    }
    return vec.end();
}

int main() {
    std::vector<int> vec {1,2,3,4,10};
    std::vector<int>::iterator res = find_it(vec, 1);
    std::cout << *(*res) << std::endl;
    return 0;
}

CodePudding user response:

vec is passed by-value, it'll be destroyed when find_it returns, the returned iterator to it is dangling, dereference on the iterator leads to UB.

You can change it to pass-by-reference.

template <typename T>
typename std::vector<T>::iterator find_it(std::vector<T>& vec, const int target){
    typename std::vector<T>::iterator it = vec.begin();
    while(it != vec.end() ){
        if(*it == target) return it;
        it  ;
    }
    return vec.end();
}

CodePudding user response:

Your find_it function copies the original vector and returns an iterator to the copy.

  •  Tags:  
  • c
  • Related