简体   繁体   中英

C++: Return the iterator pointing to element equally to the target

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;
}

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();
}

您的find_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