简体   繁体   English

如何从对象获取stl容器的类型?

[英]How to get the type of stl container from object?

How to get the type of STL container from an object? 如何从对象中获取STL容器的类型? For example, I have a container variable and I know that it is std::vector<some type> . 例如,我有一个container变量,我知道它是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. 我也不是在使用C ++ 11。

C++11 has some nice simple ways: C ++ 11有一些很简单的方法:

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. 如果编译器知道它是什么类型,那么你也是。

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). 你也有iterator typedef(你可以用而不是const_iterator)。 If you're using c++11 though, use auto, or the for(auto& value: container) { ... } form. 如果您使用的是c ++ 11,请使用auto或for(auto& value: container) { ... }表单。

to get it from type: 从类型中获取它:

container::value_type.

For associative containers; 对于关联容器; container::mapped_type (container::value_type corresponds to pair). container::mapped_type (container :: value_type对应于pair)。 It is according to Chapter 23 of C++ Standard. 这是根据C ++标准的第23章。

use boost::is_same to compare types 使用boost :: is_same来比较类型

to get it from object instance: 从对象实例获取它:

auto it = container.begin();

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: 根据具体情况, auto也可能有用:

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. 后者需要C ++ 11,但前者在C ++ 98/03中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM