【问题标题】:How to convert a vector of integer arrays into a 2D array in C++?如何在 C++ 中将整数数组向量转换为二维数组?
【发布时间】:2019-07-21 19:37:29
【问题描述】:

因此,我一直在查看以下帖子,将向量转换为数组,但这种方法似乎不适用于我的用例。

How to convert vector to array

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++ 数组

【问题讨论】:

  • vector&lt;int[256]&gt; 看起来已经很奇怪了,应该是std::vector&lt;std::array&lt;int,256&gt;&gt;
  • 我不认为你可以在实践中首先使用vector&lt;int[256]&gt;。你如何在其中插入元素?
  • 一个数组衰减为一个指针(在这种情况下为int *)。数组数组衰减为指向数组的指针 (int *[SIZE]),而不是双指针。获取table[0][0] 的地址提供了一个指向该元素的指针,即int *。用int ** 制作一个二维数组需要一些工作,而且通常是完成这项工作的效率最低的方法。如果我努力坚持下去,这条评论中可能包含一个很好的正式答案。
  • 就 eerorika 和 πάντα ῥεῖ 而言,我在使用 C 样式数组方面没有任何问题,但我现在正在考虑将其重做为 CPP 数组,看看这是否能解决我的问题
  • @yeroc_sebrof int** 附带的本机指针算法将根据可以使用简单公式 _addr = base_addr + (row_index * row_size) + col_index 寻址的连续内存块计算偏移量

标签: c++ arrays c++11 vector


【解决方案1】:

虽然会有一条应该通过强制转换工作的路由,但我可以保证最简单的方法是创建一个指向ints 的指针数组,其中包含指向源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 **,您似乎一直无法这样做,如果可能,请尝试改用a simple matrix class

【讨论】:

    【解决方案2】:

    假设使用 C++ 11,include &lt;algorithm&gt;

    你可能会使用 std::copy。

    我没有测试过,但相信你可以这样做:

    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

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 1970-01-01
      • 2018-08-08
      • 2012-03-08
      • 2019-07-30
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多