3

How to declare an iterator for unknown STL container? for example, I want to write a function that recieve container and print it all using iterators:

template <class Container> void print(Container c) {
    // how to declare iterator???????
    my_iterator = c.begin();
    while(my_iterator!=c.end()) {
        cout << *my_iterator << endl;
        my_iterator++;
    }
}
3
  • 3
    c++11: auto it = c.begin(); Commented Jun 21, 2013 at 11:13
  • 1
    It's not "unknown" - knowing template type argument is as good as knowing the type :) Commented Jun 21, 2013 at 11:14
  • 1
    Note that in this particular case, you should pass the container by const reference, to avoid making an unnecessary copy. Commented Jun 21, 2013 at 11:26

2 Answers 2

10

In C++03, you would need to get the iterator type from the container type explicitly:

typename Container::iterator it;
typename Container::const_iterator cit;

In C++11, you can just use auto:

auto my_iterator = c.begin();  // iterator in this case
auto my_iterator = c.cbegin(); // const_iterator always

Also note, as suggested my @Matthieu, that you can use a range based for loop in C++11, to simplify the code:

template <class Container> 
void print(const Container& c)
{
    for (const auto& elem : c)
        cout << c << endl;
}
Sign up to request clarification or add additional context in comments.

2 Comments

In C++11, there is actually even better: for (auto const& element: c)
@MatthieuM. of course, good point! I was concentrating on a literal interpretation of the question. I will add something about the range based loop.
0

Go for:

for (auto& var : container)
{
  cout << var << endl;
}

To display each elements of your container (and of any other type of container, even string or vector or map , ...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.