Home > Software engineering >  Can I get a container object from an iterator?
Can I get a container object from an iterator?

Time:02-20

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

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

How should I write get_vec_from_it function in the above example?

CodePudding user response:

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

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

Functions that work on a range of elements typically take a pair of iterators, first and last, to know where to stop (alternatively a first iterator and number of elements can be used). Your idea of using it!=get_vec_from_it(it).end() is overcomplicating the issue. Just pass vec.end() to the function and use that: it != end.

CodePudding user response:

No.

You can create a vector from a pair of iterators, or an iterator and number of elements. Example:

std::vector<int>
get_vec_from_its(std::vector<int>::iterator first, std::vector<int>::iterator last){
    return std::vector<int>(first, last);
}

// ...
if(vec == get_vec_from_it(vec.begin(), vec.end())){

The function is of course so trivial that I would recommend instead to use the constructor directly.

  • Related