Humam Helfawi
Humam Helfawi

Reputation: 20274

copying a container that was passed by iterators

I have function that accepts container by begin and end :

template <class Titerator>  int foo(const Titerator& begin_data, const Titerator& end_data);

inside this function I want to do something like:

While there is reaming data{
  Do something on the remaining data
  delete some of the remaining data that satisfied a condition
}

Of course reaming data is a copy of the original data (original data will not be changed)

I can not think of a way to do it . I need to copy the data so I can do what ever I want on it but how to copy it while I do not know what the is the container? is it a vector, a list or what? I just have the begin and end. How can I define this function without loosing the generic concept ?

Upvotes: 2

Views: 191

Answers (1)

If you want to create a copy of the data, you shouldn't care about what container it's originally in. That's the beauty of iterators: you don't have to care.

Choose the container for the copy based on the operations you want to do on that copy.

  • Want frequent deletions in the middle? Consider std::list.
  • Want cache-friendly, contiguous access? Consider std::vector.
  • ... and so on.

Like this:

template <class Titerator>
int foo(const Titerator& begin_data, const Titerator& end_data)
{
  std::list<typename std::iterator_traits<Tierator>::value_type> myCopy{begin_data, end_data};
  // work on myCopy
}

Upvotes: 3

Related Questions