双矢量结构

structure of double vectors

本文关键字:结构      更新时间:2023-10-16

我正试图在C++中创建一个双向量结构。

struct distance{
    vector<double> x(10000);
    vector<double> y(10000);
    vector<double> z(10000);
};
distance distance_old, distance_new;

在定义中,它抛出了一个错误:

error: expected identifier before numeric constant
error: expected ‘,’ or ‘...’ before numeric constant 

我哪里错了?

我看过这篇文章向量C的结构++但它似乎对我不起作用。

您正试图构造结构中的向量,但这是无法完成的。你必须像普通类一样在构造函数中完成:

struct distance
{
    vector<double> x;
    vector<double> y;
    vector<double> z;
    distance()
        : x(10000), y(10000), z(10000)
        { }
};

不能在结构声明中调用向量构造函数。去掉结构声明中的(10000)。如果你想使用非默认的向量构造函数来设置向量的初始容量,你需要在结构的构造函数中这样做。

一个打字错误,本质上——你需要

vector<double> x[10000];
...

括号错误!

此外,严格地说,您实际上定义的是一个向量数组,而不是双向量,即vector< vector<double> >。根据你的目的,两者都可以。

EDIT:此解决方案使用g++编译并且没有运行时错误。

dist.h:

#include <vector>
using namespace std;
struct my_distance{
    vector<double> x[10000];
    vector<double> y[10000];
    vector<double> z[10000];
};

dist.cpp:

#include "dist.h"
my_distance distance_old, distance_new;
int main()
{
    return 0;
}

NB"distance"已经被STL用于其他用途,因此必须重命名。