簡體   English   中英

C++:將指向元素的迭代器等同於目標返回

[英]C++: Return the iterator pointing to element equally to the target

我想找出指向等於目標的元素的迭代器。

以下代碼對我不起作用,這段代碼有什么問題?

#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是按值傳遞的,當find_it返回時它會被銷毀,返回給它的迭代器是懸空的,對迭代器的取消引用導致 UB。

您可以將其更改為按引用傳遞。

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