将数组推入向量 [英] Pushing an array into a vector

查看:134
本文介绍了将数组推入向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2d数组,例如 A [2] [3] = {{1,2,3},{4,5,6}}; 我想把它推入一个2D向量(向量的向量)。我知道你可以使用两个 for循环将元素一个接一个推到第一个向量,然后推到另一个向量,这使它的2d向量,但我想知道如果在C ++中有任何方式在单个循环中做到这一点。例如我想做这样的事情:

I've a 2d array, say A[2][3]={{1,2,3},{4,5,6}}; and I want to push it into a 2D vector(vector of vectors). I know you can use two for loops to push the elements one by on on to the first vector and then push that into the another vector which makes it 2d vector but I was wondering if there is any way in C++ to do this in a single loop. For example I want to do something like this:

myvector.pushback(A[1]+3); // where 3 is the size or number of columns in the array.

我知道这不是一个正确的代码,但我只是为了理解目的。感谢

I understand this is not a correct code but I put this just for understanding purpose. Thanks

推荐答案

新的C ++ 0x标准定义 initializer_lists 您:

The new C++0x standard defines initializer_lists which allows you to:

vector<vector<int>> myvector = {{1,2,3},{4,5,6}};

gcc 4.3+和一些其他编译器有部分C ++ 0x支持。
for gcc 4.3+你可以通过添加标志来启用c ++ 0x支持 -std = c ++ 0x

gcc 4.3+ and some other compilers have partial C++0x support. for gcc 4.3+ you could enable c++0x support by adding the flag -std=c++0x

这不是让你的静态数据表示的最好的方法。但是,如果你的编译器供应商支持C ++ tr1,你可以这样做:

Its not the best way to have your static data represented like that. However, if your compiler vendor supports C++ tr1 then you could do:

#include <tr1/array>  // or #include <array>
...

typedef vector<vector<int> > vector2d;
vector2d myvector;

// initialize the vectors
myvector.push_back(vector<int>());
myvector.push_back(vector<int>());

typedef std::array<std::array<int, 3>, 2> array2d;
array2d array = {{1,2,3},{4,5,6}};
array2d::const_iterator ai = array.begin(), ae = array.end();
for (vector2d::iterator i = myvector.begin(), e = myvector.end()
    ; i != e && ai != ae
    ; i++, a++)
{
    // reserve vector space
    i->reserve(array.size());

    // copy array content to vector
    std::copy(ai.begin(), ai->end(), i->begin());
}

这篇关于将数组推入向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆