如何将整数数组的向量转换为C 中的2D数组

How to convert a vector of integer arrays into a 2D array in C++?

本文关键字:数组 中的 2D 转换 整数 向量      更新时间:2023-10-16

,所以我一直在研究以下帖子,以将向量转换为数组,但是此方法似乎并未转换为我的用例。

如何将向量转换为数组

vector<array<int, 256>> table; // is my table that I want to convert
// There is then code in the middle that will fill it
int** convert = &table[0][0] // is the first method that I attempted
convert = table.data(); // is the other method to convert that doesn't work

我相信我对数据类型后端的理解是我的知识不足。对此的任何帮助将不胜感激

编辑:我已将表格C样式数组更改为C 数组

虽然应该有一条应通过铸造来工作的路线,但我可以保证的最简单的事情是将一系列指针送到 int s,其中包含指向阵列的指针源vector

// make vector of pointers to int
std::vector<int*> table2(table.size());
// fill pointer vector pointers to arrays in array vector
for (int i = 0; i < size; i++ )
{
    table2[i] = table[i];
}

示例:

#include <vector>
#include <iostream>
#include <iomanip>
#include <memory>
constexpr int size = 4;
// test by printing out 
void func(int ** arr)
{
    for (int i = 0; i < size; i++ )
    {
        for (int j = 0; j < size; j++ )
        {
            std::cout << std::setw(5) << arr[i][j] <<  ' ';
        }
        std::cout << 'n';
    }
}
int main()
{
    std::vector<int[size]> table(size);
    // fill values
    for (int i = 0; i < size; i++ )
    {
        for (int j = 0; j < size; j++ )
        {
            table[i][j] = i*size +j;
        }
    }
    // build int **
    std::vector<int*> table2(table.size());
    for (size_t i = 0; i < size; i++ )
    {
        table2[i] = table[i];
    }
    //call function
    func(table2.data());
}

看来您是因为对int **的要求而陷入困境,但请尝试使用简单的矩阵类。

假设使用C 11,include <algorithm>

您可能可以使用std ::复制。

我没有测试过,但相信您可以做:

std::copy(&table[0][0], &table[0][0]+256*table.size(), &myArray[0][0]);

参数有效:

std::copy(<source obj begin>, <source obj end>, <dest obj begin>);

在此处进行更多信息:https://en.cppreference.com/w/cpp/algorithm/copy