[英]value_type error when using STL containers with boost range adaptors
[英]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_type
, size_type
, difference_type
, reference
, key_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.