[英]converting matrix to std::vector
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? 如何将其转换为std :: vector?
You can use the two iterator constructor to instantiate a vector with a copy of of the data in wins
: 您可以使用两个迭代器构造函数来实例化带有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. 这依赖于指针算法,指针是迭代器的事实以及2D数组是连续块的事实,本质上是具有灵巧索引的1D数组。
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. 由于我不知道您是否想要2D向量,因此我将处理2D情况,因为juanchopanza处理了1D情况。 :) If you're using C++11, then you can just do this: :)如果您使用的是C ++ 11,则可以执行以下操作:
#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. 本示例使用C ++ 11初始化程序列表创建类似的结构,也称为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! 希望这可以帮助! :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.