简体   繁体   中英

Can I use value_type on an instance of the vector, not on its type

while playing and trying to calculate total size of vector I tried something like

vector<double> vd;
auto area = vd.size()* sizeof (vd::value_type); 
//Ive seen Stepanov use area as name for this kind of size, idk if he adds the sizeof vd also to area :)

Unfortunately this doesnt work... I need to use vector<double>::value_type but that makes code less readable. Can it be made to work? I dont like sizeof vd.front() because it just looks ugly to write front() for this.
EDIT: decltype variants also fit in what I would call ugly category...

I think decltype can be used:

auto area = vd.size() * sizeof(decltype(vd)::value_type);

as you are using auto I assume C++11 is permitted.

Confirmed with g++ v4.7.2 and clang v3.3.

How about a simple helper function?

template <typename Container>
size_t value_size(const Container &)
{
    return sizeof(typename Container::value_type);
}

[...]

vector<double> vd;
auto area = vd.size() * value_size(vd);

You could even overload the function so that it works with other containers such as arrays (of course, you would need to wrap size as well).

Ideally, the entire computation could be wrapped into a generic function:

template <typename Container>
size_t area(const Container &c)
{
    return c.size() * sizeof(typename Container::value_type);
}

//possible overload for arrays (not sure it's the best implementation)
template <typename T, size_t N>
size_t area(const T (&arr)[N])
{
    return sizeof(arr);
}

[...]

std::vector<double> vd;
auto vd_area = area(vd);
double arr[] = { 1., 2. };
auto arr_area = area(arr);

In C++11, you could use decltype(vd[0]) :

auto area = vd.size()* sizeof (decltype(vd[0])); 

But in the particular scenario, you could just write this:

auto area = vd.size()* sizeof (vd[0]); 

Since the expression inside sizeof (and decltype too) will not be evaluated, both will work even if vd is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM