簡體   English   中英

在STL容器中使用value_type有什么用?

[英]What is the use of value_type in STL containers?

在STL容器中使用value_type什么用?

來自MSDN:

// vector_value_type.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>

int main( )
{
   using namespace std;
   vector<int>::value_type AnInt;
   AnInt = 44;
   cout << AnInt << endl;
}

我不明白value_type在這里具體實現了什么? 變量也可以是int 是否使用是因為編碼人員懶得檢查向量中存在的對象類型是什么?

一旦我清楚這一點,我想我將能夠理解allocator_typesize_typedifference_typereferencekey_type等。

是的,在您的示例中,很容易知道您需要一個int 通用編程很復雜。 例如,如果我想編寫一個通用的sum()函數,我需要它知道迭代什么類型的容器以及它的元素是什么類型,所以我需要這樣的東西:

template<typename Container>
typename Container::value_type sum(const Container& cont)
{
    typename Container::value_type total = 0;
    for (const auto& e : cont)
        total += e;
    return total;
}

暫無
暫無

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

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