简体   繁体   English

C++:将指向元素的迭代器等同于目标返回

[英]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. vec是按值传递的,当find_it返回时它会被销毁,返回给它的迭代器是悬空的,对迭代器的取消引用导致 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函数复制原始向量并将迭代器返回到副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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