converting matrix to std::vector

ぃ、小莉子 提交于 2019-12-11 06:09:28

问题


I have the following matrix:

unsigned wins[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };

how to convert it into a std::vector?


回答1:


You can use the two iterator constructor to instantiate a vector with a copy of of the data in wins:

unsigned* start = &wins[0][0];
std::vector<unsigned> vwins(start, start + (8 * 3));

This relies on pointer arithmetic, the fact that pointers are iterators, and the fact that 2D arrays are contiguous blocks, essentially 1D arrays with clever indexing.




回答2:


Since I don't know whether you want a 2D vector or not, I'll handle the 2D case since juanchopanza handled the 1D case. :) If you're using C++11, then you can just do this:

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

int main()
{
    vector<vector<int>> wins = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
    for(vector<int> & row : wins) {
        for(int &col : row) {
            cout << col << " ";
        }
        cout << endl;
    }
    return 0;
}

This example uses C++11 initializer lists to create an analogous structure, also called wins. I also wrote a little code to show how you could loop through it to print it out in a sensical order.

Hope this helps! :)



来源:https://stackoverflow.com/questions/19874162/converting-matrix-to-stdvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!