【问题标题】:C++ - Vector of Float ArraysC++ - 浮点数组的向量
【发布时间】:2015-11-14 18:35:00
【问题描述】:

我目前正在尝试创建一个包含浮点数组的向量。我的日子不好过。

我有以下代码:

float testArray[4] = {20, -3.14/2, 5, -3.14/2};
std::vector<float[4]> inputVector;
std::vector<float[4]>::iterator it = inputVector.begin();
inputVector.insert(it, testArray);

我不断收到错误消息,说“数组必须使用大括号括起来的初始化程序进行初始化”和“无效的数组分配”。我用整数向量(而不是数组向量)尝试了相同的代码,没有任何问题。

我认为存在一个我不理解的潜在问题。

感谢任何帮助!

【问题讨论】:

标签: c++ arrays vector


【解决方案1】:

使用std::array。 C 风格的数组通常不应该在现代 C++ 代码中使用。

#include <vector>
#include <array>

int main()
{
  std::array<float, 4> testArray{{20, -3.14/2, 5, -3.14/2}};
  std::vector<std::array<float, 4>> inputVector;
  std::vector<std::array<float, 4>>::iterator it = inputVector.begin();
  inputVector.insert(it, testArray);
}

阅读这些问题/答案以获取更多信息:


请注意,这将复制数组及其所有内容。如果要引用现有的testArray 实例,则创建一个std::vector&lt;std::array&lt;float, 4&gt;*&gt;,并在将其插入向量时取实例的地址:inputVector.insert(it, &amp;testArray);

【讨论】:

  • @tobi303:我使用std::array 代替float[4],而不是代替std::vector。 C 风格的数组在现代 C++ 代码中没有用处。
  • ups 对不起,我发废话有点快;)
  • @VittorioRomeo 当您通过串行链路之类的方式传输阵列时会怎样?那我可以使用 C 风格的数组吗?
  • @Sam:在那种情况下你为什么不能使用std::array
  • @VittorioRomeo 因为你有 std::array.data 你没有数组类存储的任何辅助信息(想到大小)。
【解决方案2】:

这个怎么样:-

float t[4] = {20, -3.14/2, 5, -3.14/2};
float *testArray=t;
std::vector<float*> inputVector;
std::vector<float*>::iterator it = inputVector.begin();
inputVector.insert(it, testArray);

最好使用std::array&lt;float, 4&gt; 而不是in-built arrays。您以前的代码的问题是您正在尝试类似的东西:-

float a[4] {1.1, 2.2, 3.3, 4.4};
float b[4] = a;   // illegal conversion of float[] to float*

因此您的代码曾经失败

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多