向量不取消引用?

问题描述

#include <iostream>
using namespace std;
#include <vector>

int **function(vector<int> *nums,int rows){
  int **output = new int*[3];
  int index;
  for (int i = 0; i < rows; i++){
    for (int j = 0; j < 3; j++){
      index = (3*i)+j;
      output[i][j] = nums[index];
    }
  }
  return output;
}

int main(void){
  int array[3][3] = {{1,4,3},{4,2,6},{7,3,7}};
  vector<int> nums;
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      nums.push_back(array[i][j]);
    }
  }

  int **dbl = function(&nums,3);
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      cout << dbl[i][j] << " ";
    }
    cout << endl;
  }
}

因此,我试图将2d数组放入向量中并将其放入双指针中,但是当我尝试使用索引取消引用nums时,出现从向量分配int的错误。不应自动取消引用向量吗?我无法用其他任何方式做到;这是使用向量的大型项目的一部分。

解决方法

您的函数function()使用指向vectorvector的数组)的指针,但是您只有一个向量。

还要注意,rows元素应该分配给output而不是3,并且应该为每行分配数组。

您想要的可能是这样:

#include <iostream>
using namespace std;
#include <vector>

int **function(const vector<int>& nums,int rows){ // use reference instead of pointer
  int **output = new int*[rows]; // allocate rows elements
  int index;
  for (int i = 0; i < rows; i++){
    output[i] = new int[3]; // allocate each row
    for (int j = 0; j < 3; j++){
      index = (3*i)+j;
      output[i][j] = nums[index]; // now index applies to the vector instead of the pointer (array of vector)
    }
  }
  return output;
}

int main(void){
  int array[3][3] = {{1,4,3},{4,2,6},{7,3,7}};
  vector<int> nums;
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      nums.push_back(array[i][j]);
    }
  }

  int **dbl = function(nums,3); // don't use pointer: use reference instead
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      cout << dbl[i][j] << " ";
    }
    cout << endl;
  }
}

如果要使用指向向量的指针,请先取消引用以访问向量的元素:

#include <iostream>
using namespace std;
#include <vector>

int **function(vector<int> *nums,int rows){
  int **output = new int*[rows]; // allocate rows elements
  int index;
  for (int i = 0; i < rows; i++){
    output[i] = new int[3]; // allocate each row
    for (int j = 0; j < 3; j++){
      index = (3*i)+j;
      output[i][j] = (*nums)[index]; // dereference the pointer
      // alternative way
      // output[i][j] = nums->at(index);
    }
  }
  return output;
}

int main(void){
  int array[3][3] = {{1,7}};
  vector<int> nums;
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      nums.push_back(array[i][j]);
    }
  }

  int **dbl = function(&nums,3);
  for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
      cout << dbl[i][j] << " ";
    }
    cout << endl;
  }
}