簡體   English   中英

如何在C ++中將整數數組的向量轉換為2D數組?

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

因此,我一直在看以下將向量轉換為數組的文章,但是對於我的用例來說,這種方法似乎沒有轉換。

如何將向量轉換為數組

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 ++數組

假設使用C ++ 11,請include <algorithm>

您可能使用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

雖然將有一條應該通過強制轉換起作用的路由,但我可以保證的最簡單的方法是使一個指向int的指針數組,該數組包含指向源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 **的要求,您似乎一直無法做到這一點,請盡可能嘗試使用簡單的矩陣類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM