What is the use of value_type in STL containers?

允我心安 提交于 2020-08-01 06:29:11

问题


What's the use of value_type in STL containers?

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

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?

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


回答1:


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


来源:https://stackoverflow.com/questions/44571362/what-is-the-use-of-value-type-in-stl-containers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!