Reputation: 347
I need a way to convert data in the form of std::vector<std::array<int, 2> >
into std::vector<std::vector<int> >
quickly.
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?
Upvotes: 0
Views: 492
Reputation: 88017
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.
Upvotes: 2