簡體   English   中英

如何從對象獲取stl容器的類型?

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

如何從對象中獲取STL容器的類型? 例如,我有一個container變量,我知道它是std::vector<some type> 我需要使用迭代器迭代容器。 有沒有辦法在不知道容器類型的情況下聲明迭代器?

我當然可以從代碼中獲取類型,但我很樂意在不使用類型的情況下完成它。 我也不是在使用C ++ 11。

C ++ 11有一些很簡單的方法:

auto it = container.begin();

或等效地:

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

甚至:

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

盡管如此,即使您不能使用類型推導,也不應該處於無法以某種形式輸入類型(可能涉及模板參數)的情況。 如果編譯器知道它是什么類型,那么你也是。

typedef std::vector<some_type> container;

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

你也有iterator typedef(你可以用而不是const_iterator)。 如果您使用的是c ++ 11,請使用auto或for(auto& value: container) { ... }表單。

從類型中獲取它:

container::value_type.

對於關聯容器; container::mapped_type (container :: value_type對應於pair)。 這是根據C ++標准的第23章。

使用boost :: is_same來比較類型

從對象實例獲取它:

auto it = container.begin();

一種方法是使用模板:

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);
}

根據具體情況, auto也可能有用:

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

后者需要C ++ 11,但前者在C ++ 98/03中可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM