【问题标题】:C++ how to push_back an array int[10] to std::vector<int[10]>?C ++如何将数组int [10]推回std :: vector <int [10]>?
【发布时间】:2016-11-07 23:30:59
【问题描述】:
#include <vector>
using namespace std;

vector<int[60]> v;
int s[60];
v.push_back(s);

Visual Studio 2015 社区中的这段代码报告编译错误:

错误(活动)没有重载函数实例“std::vector<_ty _alloc>::push_back [with _Ty=int [60], _Alloc=std::allocator]”与参数列表匹配

错误 C2664 'void std::vector>::push_back(const int (&)[60])':无法将参数 1 从 'int' 转换为 'int (&&)[60]'

【问题讨论】:

  • 你应该使用std::array,原始数组很挑剔,一旦你看到它们就会衰减到指向它们的第一个元素的指针。
  • int[10] s; 是一个语法错误,您也应该在该行遇到问题。 v.push_back(s) 也必须出现在函数内部
  • 对不起,我弄错了

标签: c++ arrays vector stl


【解决方案1】:

请改用std::array

#include <vector>
#include <array>

using namespace std;

int main()
{
    vector<array<int, 10>> v;
    array<int, 10> s;
    v.push_back(s);
    return 0;
}

但我也不得不质疑包含数组的向量的目的。无论其根本原因是什么,都可能有更好的方法来实现相同的目标。

【讨论】:

  • 我在一个函数中生成了一些 int 数组,每个数组都是一个 int[60] 数组。我想在函数结束时返回所有这些数组。所以我想我需要一个像vector v这样的容器,当我生成一个新数组时,我可以将新的int数组推入vector。
  • 对数组本身使用std::vector。你显然对std::vector了如指掌。
【解决方案2】:

你可以这样做:

#include <iostream>
#include <vector>

int main()
{
    int t[10] = {1,2,3,4,5,6,7,8,9,10};

    std::vector<int*> v;

    v.push_back(t);

    std::cout << v[0][4] << std::endl;

   return 0;
}

更具体地说,在这个解决方案中,您实际上并没有将数组 t 的值存储到向量 v 中,您只是存储指向数组的指针(并且更具体到数组的第一个元素)

【讨论】:

  • 我认为你的方法和 std::array 都符合我的要求。谢谢。
【解决方案3】:

我不确定你是说从数组中初始化一个向量,如果是的话,这里有一种使用向量构造函数的方法:

int s[] = {1,2,3,4};
vector<int> v (s,  s + sizeof(s)/sizeof(s[0]));

【讨论】:

  • sizeof(s) - 这可能很棘手,因为您可以使用 int s[] 作为函数参数,它将转换为 int* s,您将获得 sizeof(int*)
  • 你是对的,基于这篇文章:stackoverflow.com/questions/4108313/… 我假设他使用的是 C 风格的数组,正如他在 OP 中所说的那样
  • 不,我需要使用容器收集大量数组,例如向量。每个数组都是一个 int[60]。
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 2020-01-26
  • 2014-03-03
  • 1970-01-01
相关资源
最近更新 更多