简体   繁体   English

如何计算向量的大小

[英]How to calculate size of a vector

I need calculate memory (static and dynamic) taken by the vector myVec; 我需要计算向量myVec占用的内存(静态和动态); I have calculated the size in following manner 我已经按照以下方式计算了尺寸

size = sizeof(myVec) * myVec.size();

I need to know the what I did is correct or not ? 我需要知道我做的正确与否吗?

struct S1
{
  vector<int> v1;
  IplImage* image;
  vector<CvRect> rect;
};

struct S2
{
  vector<S1> var1;
  vector<int>  var2;
  IplImage* img1;
};

vector<S2> myVec;


//size = sizeof(myVec) * myVec.size(); ?????

You cannot easily determine both the static and dynamic size of a container in C++, because each contained instance can allocate its own internal memory (as @enhzflep pointed out in comments). 您不能轻易确定C ++中容器的静态和动态大小,因为每个包含的实例都可以分配自己的内部内存(如@enhzflep在注释中指出的那样)。

However, if you really need to do that, and if you know what types you might want to store in your container, you might use templates to assemble the final algorithm for you. 但是,如果确实需要这样做,并且知道要在容器中存储什么类型,则可以使用模板为您组装最终算法。 Ie, something along the lines of: 即,类似于以下内容:

template<typename T>
struct compute_size {
    static unsigned of(const T& t) {
        assert(false && "not implemented");
        return 0;
    }
};

template<typename T>
struct compute_size<std::vector<T>> {
    static unsigned of(const std::vector<T>& v) {
        // static size
        unsigned result = sizeof(std::vector<T>);
        // static and dynamic size of all used elements
        for(auto& i : v)
            result += compute_size<T>::of(i);
        // account for allocated empty space
        result += (v.capacity() - v.size()) * sizeof(T);

        return result;
    }
};

template<>
struct compute_size<int> {
    static unsigned of(const int&) {
        return sizeof(int);
    }
};

template<>
struct compute_size<std::string> {
    static unsigned of(const std::string& s) {
        return sizeof(std::string) + s.capacity() * sizeof(std::string::value_type);
    }
};

Used via a function template: 通过功能模板使用:

template<typename T>
unsigned get_size(const T& val) {
    return compute_size<T>::of(val);
}

Leading to something like: 导致类似:

std::vector<std::string> qqq;
qqq.push_back("asdfasdf");
qqq.push_back("qwer");
std::cout << get_size(qqq) << std::endl;

With some possible optimisations like: 有一些可能的优化,例如:

// for PODs we don't really have to iterate
template<>
struct compute_size<std::vector<int>> {
    static unsigned of(const std::vector<int>& v) {
        return sizeof(v) + v.capacity() * sizeof(int);
    }
};    

And, possibly, generalizing this to whole groups of types using std::enable_if . 并且可能使用std::enable_if推广到整个类型的组。

Static size : sizeof(vector<S2>) 静态大小: sizeof(vector<S2>)

Dynamic size : myVec.capacity() * sizeof(S2) 动态大小: myVec.capacity() * sizeof(S2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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