我可以从迭代器获取容器对象吗?

Hay*_*aki 0 c++ stl stdvector

std::vector<int> vec={1,2,3};
std::vector<int>::iterator it = vec.begin();

if(vec == get_vec_from_it(it)){
  puts('sucesss');
}
Run Code Online (Sandbox Code Playgroud)
std::vector<int> get_vec_from_it(std::vector<int>::iterator it){
/*?*/
}

Run Code Online (Sandbox Code Playgroud)

get_vec_from_it上面例子中的函数应该怎么写?

for*_*818 5

The basic idea is that iterators abstract away where the elements come from, there might not even be a container. Afaik there is a single type of iterator that "knows" its container and that is std::back_insert_iterator, though thats an exception. The container member is only protected so there is even a way to get the container from a std::back_insert_iterator, but thats not how it is meant to be used.

You can adance the iterator to get the next element, but you wouldn't know where to stop, because at some point you'll reach the end of the vector and there is no way to identify it. If you pass begin and end you can create a copy of the original vector:

std::vector<int> get_vec_from_it(std::vector<int>::iterator begin ,std::vector<int>::iterator end){
    return {begin,end};
}
Run Code Online (Sandbox Code Playgroud)

Though, thats just a different way to copy the vector and you need to know both begin and end.


I made a function that returns the iterator that points to the node but I couldn't write the stop condition in a for statement. So I wonder if the stop condition can be written like it!=get_vec_from_it(it).end()

作用于一系列元素的函数通常需要一对迭代器,firstlast来知道在哪里停止(或者first可以使用迭代器和元素数量)。您的使用想法it!=get_vec_from_it(it).end()使问题过于复杂化。只需传递vec.end()给该函数并使用它:it != end