Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Generic" iterator in c++

Tags:

c++

iterator

stl

I have:

void add_all_msgs(std::deque<Message>::iterator &iter);

How can I make that function "generic", so it can take any kind of inputiterators ? I don't really care if it's iterating a deque,a vector or something else, as long as the iterator is iterating Message's. - is this at all straight forward possible in c++ ?

like image 805
nos Avatar asked Jul 09 '09 13:07

nos


People also ask

What is iterator in C language?

An iterator is an object that allows you to step through the contents of another object, by providing convenient operations for getting the first element, testing when you are done, and getting the next element if you are not. In C, we try to design iterators to have operations that fit well in the top of a for loop.

What is iterator and it types?

Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent.

What is a vector iterator?

An iterator is used to move thru the elements an STL container (vector, list, set, map, ...) in a similar way to array indexes or pointers. The * operator dereferences an iterator (ie, is used to access the element an iterator points to) , and ++ (and -- for most iterators) increments to the next element.

What is iterator type in C++?

An iterator is an object that can iterate over elements in a C++ Standard Library container and provide access to individual elements.


1 Answers

template <typename Iterator>
void add_all_messages(Iterator first, Iterator last)

usage :

vector<message> v;
add_all_messages(v.begin(), v.end());

You need to specify the end, otherwise you won't know when to stop! It also gives you the flexibility of adding only a subrange of a container.

like image 114
Edouard A. Avatar answered Sep 21 '22 15:09

Edouard A.