C++ 使用数组向量的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4612273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:55:36  来源:igfitidea点击:

Correct way to work with vector of arrays

c++arraysvectorstdvector

提问by Pulkit Sinha

Could someone tell what is the correct way to work with a vector of arrays?

有人能说出使用数组向量的正确方法是什么吗?

I declared a vector of arrays (vector<float[4]>) but got error: conversion from 'int' to non-scalar type 'float [4]' requestedwhen trying to resizeit. What is going wrong?

我声明了一个数组向量 ( vector<float[4]>) 但error: conversion from 'int' to non-scalar type 'float [4]' requested在尝试时得到resize了。出了什么问题?

回答by James McNellis

You cannot store arrays in a vectoror any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.

您不能将数组存储在vector或任何其他容器中。要存储在容器中的元素的类型(称为容器的值类型)必须是可复制构造和可赋值的。数组两者都不是。

You can, however, use an arrayclass template, like the one provided by Boost, TR1, and C++0x:

但是,您可以使用array类模板,例如 Boost、TR1 和 C++0x 提供的类模板:

std::vector<std::array<double, 4> >

(You'll want to replace std::arraywith std::tr1::arrayto use the template included in C++ TR1, or boost::arrayto use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)

(您想更换std::arraystd::tr1::array使用包含在C ++ TR1的模板,或者boost::array使用从Boost库的模板或者,你可以写你自己的。这是非常简单的。)

回答by Nawaz

Use:

用:

vector<vector<float>> vecArray; //both dimensions are open!

回答by Nawaz

There is no error in the following piece of code:

下面这段代码没有错误:

float arr[4];
arr[0] = 6.28;
arr[1] = 2.50;
arr[2] = 9.73;
arr[3] = 4.364;
std::vector<float*> vec = std::vector<float*>();
vec.push_back(arr);
float* ptr = vec.front();
for (int i = 0; i < 3; i++)
    printf("%g\n", ptr[i]);

OUTPUT IS:

输出是:

6.28

6.28

2.5

2.5

9.73

9.73

4.364

4.364

IN CONCLUSION:

综上所述:

std::vector<double*>

is another possibility apart from

是另一种可能

std::vector<std::array<double, 4>>

that James McNellis suggested.

詹姆斯麦克内利斯建议。

回答by Mark Ransom

Every element of your vector is a float[4], so when you resize every element needs to default initialized from a float[4]. I take it you tried to initialize with an intvalue like 0?

向量的每个元素都是 a float[4],因此当您调整大小时,每个元素都需要从 a 进行默认初始化float[4]。我认为您尝试使用int类似的值进行初始化0

Try:

尝试:

static float zeros[4] = {0.0, 0.0, 0.0, 0.0};
myvector.resize(newsize, zeros);