Ashot
Ashot

Reputation: 10959

How to get the type of stl container from object?

How to get the type of STL container from an object? For example, I have a container variable and I know that it is std::vector<some type>. I need to iterate the container using iterators. Is there a way to declare iterator without knowing the type of container?

I can get the type from the code of course, but I am curios to do it without using the type. Also I am not using C++11.

Upvotes: 2

Views: 7091

Answers (4)

Jerry Coffin
Jerry Coffin

Reputation: 490048

One way is with a template:

template <class container>
void dosomething(container &c) { 
    typename container::iterator it = c.begin();
    typename container::iterator end = c.end();

    while (it != end) 
       dosomething_with(*it);
}

Depending on the situation, auto may be useful as well:

for (auto it = container.begin(); it != container.end(); ++it)
    dosomething_with(*it);

The latter requires C++11, but the former is available in C++98/03.

Upvotes: 0

4pie0
4pie0

Reputation: 29724

to get it from type:

container::value_type.

For associative containers; container::mapped_type (container::value_type corresponds to pair). It is according to Chapter 23 of C++ Standard.

use boost::is_same to compare types

to get it from object instance:

auto it = container.begin();

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

C++11 has some nice simple ways:

auto it = container.begin();

Or equivalently:

decltype(container.begin()) it = container.begin();

Or even:

decltype(container)::iterator it = container.begin();

Nonetheless, even if you can't use type deduction, you should never be in a situation where you couldn't type out the type in some form or another (perhaps involving template parameters). If the compiler knows what type it is, so do you.

Upvotes: 9

utnapistim
utnapistim

Reputation: 27365

typedef std::vector<some_type> container;

for(container::const_iterator i = container.begin(); i != container.end(); ++i)
    // ... 

You also have iterator typedef (that you can use instead of const_iterator). If you're using c++11 though, use auto, or the for(auto& value: container) { ... } form.

Upvotes: 2

Related Questions