简体   繁体   English

将 arrays 的向量转换为向量的向量 c++

[英]Convert vector of arrays into vector of vectors c++

I need a way to convert data in the form of std::vector<std::array<int, 2> > into std::vector<std::vector<int> > quickly.我需要一种将std::vector<std::array<int, 2> >形式的数据快速转换为std::vector<std::vector<int> >的方法。 I have the following solution, but on large vectors this is quite slow for me.我有以下解决方案,但是在大型向量上这对我来说很慢。

std::vector<std::array<int, 2> > data; // filled with data
std::vector<std::vector<int> > mod;

for (int i = 0; i < data.size(); i++) {
   mod.push_back(vector<int>(data[i].begin(), data[i].end()));
}

Is there a more efficient way to do it?有没有更有效的方法来做到这一点?

The following should be more efficient以下应该更有效

std::vector<std::array<int, 2> > data; // filled with data
std::vector<std::vector<int> > mod;

mod.reserve(data.size());
for (int i = 0; i < data.size(); i++) {
   mod.emplace_back(data[i].begin(), data[i].end());
}

reserve prevents reallocation of the mod vector as it grows, and emplace_back constructs the smaller vectors in place, potentially avoiding some copying of data. reserve可防止mod向量在增长时重新分配,并且emplace_back会在适当位置构造较小的向量,从而可能避免一些数据复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM