简体   繁体   中英

How to create a vector of objects efficiently in C++?

vector<vector<int>> v(100, vector<int>(100)); // 101 vector<int> are created

I need to created a vector of vectors (or objects) like above. But then there will be 101 vector<int> created, which is one more I needed. If i understand it correctly, first a vector<int>(100) is created and then it's copied 100 times.

So I want to know if there's a way to avoid the reduncdant construction? Just create 100 elements.

I guess the std::vector could handle this case with move semantics emplacing the first vector(100) at index 0 and doing 99 copies. But it doesn't.

But you can easily do that yourself:

vector<vector<int>> v;
v.reserve(100);
v.emplace_back(100);
for (int i = 1; i < 100; ++i) {
    v[i] = v[0];
}

You can do the same for the inner vector if you have a Matrix of complex objects where one extra copy is bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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