2
votes

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.

4
Can you show some code where you work with std::vector of "some type"s ?LihO
Can you show some code that illustrates the problem you are having. If you have a function that is accepting the container as a parameter, then the type has to be included -- unless it's a template, but even in that case you can use SFINAE to get what you need.Chad
The compiler knows the type of the container, why don't you?Mark Ransom
The container variable is a template parameter? Is that why you don't know the specific type?Drew Dormann
That's why auto is added to C++11 !Ajay

4 Answers

9
votes

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.

2
votes
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.

1
votes

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();
0
votes

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.