STL容器中value_type的用途是什么? [英] What is the use of value_type in STL containers?

查看:39
本文介绍了STL容器中value_type的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

STL容器中 value_type 的用途是什么?

What's the use of value_type in STL containers?

从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 吗?是因为编码人员懒于检查向量中存在的对象类型是什么?

I don't understand what does value_type specifically achieve here? The variable could be an int as well? Is it used because the coders are lazy to check what's the type of objects present in the vector?

一旦我清楚这一点,我想我就能理解 allocator_type size_type difference_type reference key_type 等.

Once I am clear about this I think I will be able to understand allocator_type,size_type,difference_type,reference,key_type etc..

推荐答案

是的,在您的示例中,很容易知道您需要 int .复杂的地方是通用编程.例如,如果我想编写一个通用的 sum()函数,则需要它知道要迭代的容器类型以及其元素是什么类型,因此我需要具有类似的内容:

Yes, in your example, it is pretty easy to know that you need an int. Where it gets complicated is generic programming. For example, if I wanted to write a generic sum() function, I would need it to know what kind of container to iterate and what type its elements are, so I would need to have something like this:

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

这篇关于STL容器中value_type的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆