繁体   English   中英

如何计算向量的大小

[英]How to calculate size of a vector

我需要计算向量myVec占用的内存(静态和动态); 我已经按照以下方式计算了尺寸

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

我需要知道我做的正确与否吗?

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(); ?????

您不能轻易确定C ++中容器的静态和动态大小,因为每个包含的实例都可以分配自己的内部内存(如@enhzflep在注释中指出的那样)。

但是,如果确实需要这样做,并且知道要在容器中存储什么类型,则可以使用模板为您组装最终算法。 即,类似于以下内容:

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

通过功能模板使用:

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

导致类似:

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

有一些可能的优化,例如:

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

并且可能使用std::enable_if推广到整个类型的组。

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

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

暂无
暂无

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

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