【问题标题】:How can one change a 1d array into a 2d vector?如何将一维数组更改为二维向量?
【发布时间】:2016-08-29 08:38:51
【问题描述】:

我有一个一维数组{3,3,7,3,1,3,4,3,3,4,2,6,4,1,4,2,4,1} 而且我知道向量通常应该是 3*6 或 (m*n) 的顺序

{{3, 3, 7, 3, 1, 3},
 {4, 3, 3, 4, 2, 6},
 {4, 1, 4, 2, 4, 1}
}

我知道如何转换成二维数组,但我是矢量新手

int count =0;
for(int i=0;i<m;i++)
{
   for(int j=0;j<n;j++)
{
if(count==input.length)
   break;
a[i][j]=input[count];
count++;
}
}

【问题讨论】:

  • 不清楚你到底在问什么。
  • 使用纯数组有什么问题...您需要 中的任何特定操作吗?
  • 是的,基本上也是为了学习目的。

标签: c++ arrays vector


【解决方案1】:

本身没有“2D 向量”之类的东西,但您可以拥有向量的向量。

我认为这是你想要的:

#include <vector>
#include <iostream>

using namespace std;


int main()
{
    // make a vector that contains 3 vectors of ints
    vector<vector<int>> twod_vector(3);

    int source[18] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
    for (int i = 0; i < 3; i++) {
        // get the i-th inner vector from the outer vector and fill it
        vector<int> & inner_vector = twod_vector[i];
        for (int j = 0; j < 6; j++) {
            inner_vector.push_back(source[6 * i + j]);
        }
    }

    // to show that it was properly filled, iterate through each
    //   inner vector
    for (const auto & inner_vector : twod_vector) {
        // in each inner vector, iterate through each integer it contains
        for (const auto & value : inner_vector) {
            cout << value;   
        }
        cout << endl;
    }

}

现场观看:http://melpon.org/wandbox/permlink/iqepobEY7lFIyKcX

【讨论】:

    【解决方案2】:

    一种方法是创建一个临时向量并循环填充,然后将临时向量推入原来的std::vector&lt;std::vector&lt;int&gt;&gt;

    int array[] = { 3,3,7,3,1,3,4,3,3,4,2,6,4,1,4,2,4,1 };
    vector<vector<int>> two_dimentional;
    size_t arr_size = sizeof(array)/sizeof(array[0]);
    
    vector<int> temp;                             // create a temp vector
    for (int i{}, j{}; i != arr_size; ++i, ++j) { // loop through temp
        temp.emplace_back(array[i]);              // and add elements to temp
        if (j == 5) {                             // until j == 5
            two_dimentional.emplace_back(temp);   // push back to original vec
            temp.clear();                         // clear temp vec
            j = -1;                               // j = 0 next time around
        }
    }
    

    输出std::vector&lt;std::vector&lt;int&gt;&gt; 会显示:

    3 3 7 3 1 3
    4 3 3 4 2 6
    4 1 4 2 4 1
    

    【讨论】:

    • 你不要在 emplace 中移动 temp,所以我认为会复制 temp。你可能应该 std::move 它。但实际上,既然你知道大小,最好像我的回答一样把它们放在前面,这样以后就不会再有任何额外的分配了。
    猜你喜欢
    • 2021-01-31
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多