在 C++ 中创建一个向量数组 [英] Create an Array of vectors in C++

查看:80
本文介绍了在 C++ 中创建一个向量数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个大数据集的距离矩阵,并且只想存储足够接近"的元素.代码是这样的

I want to create a distance matrix of a big dataset, and only want to store the 'close' enough elements. The code reads like this

vector<double> * D; 
D = (vector<double> *) malloc(dim *sizeof(vector<double>) ) ;

for(i=0;i<dim;i++){
    for(j=i+1;j<dim;j++){
        dx = s[j][0] - s[i][0];
        dy = s[j][1] - s[i][1];
        d =   sqrt( dx*dx + dy*dy );
        if(d  < MAX_DISTANCE){
            D[i].push_back(d);
            D[j].push_back(d);
            }
        }

这给了我分段错误.我想我没有正确定义向量数组.我该如何解决这个问题?

which gives me segmentation fault. I guess I have not defined the array of vector correctly. How do I get around this ?

推荐答案

在 C++ 中,您应该永远使用 malloc 分配对象(或对象数组).虽然 malloc 擅长分配内存,但仅此而已.它不会做的是调用构造函数,这意味着你所有的vector对象都未初始化.使用它们会导致未定义行为.

In C++ you should never allocate object (or arrays of objects) using malloc. While malloc is good at allocating memory, that's all it does. What it doesn't do is calling constructors which means all your vector objects are uninitialized. Using them will lead to undefined behavior.

如果你想动态分配一个数组,你必须使用new[].或者,更好的是,使用 std::vector(是的,你可以有一个向量向量,std::vector> 是很好).

If you want to allocate an array dynamically you must use new[]. Or, better yet, use std::vector (yes, you can have a vector of vectors, std::vector<std::vector<double>> is fine).

使用正确的向量构造函数,您可以初始化一个向量具体尺寸:

Using the right vector constructor you can initialize a vector of a specific size:

// Create the outer vector containing `dim` elements
std::vector<std::vector<double>> D(dim);

在上述之后,您可以像以前一样使用现有的循环.

After the above you can use the existing loops like before.

这篇关于在 C++ 中创建一个向量数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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