【发布时间】:2016-05-19 04:25:12
【问题描述】:
我有 T 的向量向量:
std::vector<std::vector<T>> vector_of_vectors_of_T;
我想将它们全部合并到 T 的单个向量中:
std::vector<T> vector_of_T;
我目前正在使用这种方法:
size_t total_size{ 0 };
for (auto const& items: vector_of_vectors_of_T){
total_size += items.size();
}
vector_of_T.reserve(total_size);
for (auto const& items: vector_of_vectors_of_T){
vector_of_T.insert(end(vector_of_T), begin(items), end(items));
}
还有更直接的方法吗?像一个准备好的标准功能?如果没有,是否有更有效的手动方式?
【问题讨论】:
-
我认为这个问题更适合codereview.stackexchange.com
-
@Luca Pizzamiglio 感谢您的纠正
-
vector_of_vectors_of_T.SelectMany(...-- 哦等等,语言错误:P -
@Humam 如果您想获得太多 STL,您可以将其用于
reserve部分:vector_of_T.reserve(std::accumulate(std::begin(vector_of_vectors_of_T), std::end(vector_of_vectors_of_T), 0, [](size_t size, std::vector<T> const& vec) { return size + vec.size(); })); -
这里没有太大的改进空间,除了使用移动迭代器(如果你不再需要原来的)。这是 range-v3 中的
action::join,因此您可能会在标准中看到它……有一天。
标签: c++ algorithm c++11 vector