将STL list <string>转换为vector <string> c ++ 11

Bil*_*ore 1 c++ c++11 c++17

将列表转换为向量的最佳方法是什么?

我在考虑一个循环.但也许在C++ 11中有更好的方法?

#include <list>
#include <string>
#include <vector>
using namespace std;

list<string> list_string {
  "one",
  "two",
  "three"
};

vector<string> vector_string;
for (auto item : list_string) {
    vector_string.push_back(item);
}
Run Code Online (Sandbox Code Playgroud)

在C#中,我可以使用接受IEnumerable接口的构造函数初始化其他数据类型.很奇怪,如果C++ 11支持类似的东西......

Bar*_*rry 11

std::vector(以及任何标准容器)的构造函数之一采用一对迭代器:

template< class InputIt >
vector( InputIt first, InputIt last, 
        const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

vector<string> v(list_string.begin(), list_string.end());
Run Code Online (Sandbox Code Playgroud)

  • 我对这种方法的唯一问题是提前添加的项目数量是未知的,特别是对于来自`std :: list`的非随机访问迭代器.因此,如果性能是一个问题,并且你想在填充时减少重新分配,它*可能*值得首先构造一个空的`vector`,然后`reserve()`与`std :: list`的大小相同,最后使用`push_back()`循环或`std :: copy(_n)()`或基于范围的`std ::: vector :: insert()`等填充向量. (3认同)
  • @RemyLebeau虽然标准不能保证,[libc ++](https://github.com/llvm-mirror/libcxx/blob/1639392a4af6150c69d77bbda1327b2fbce8c293/include/vector#L1197-L1213)和[libstdc ++](https:// github.只要迭代器至少是*ForwardIterator*s,com/gcc-mirror/gcc/blob/393138d71ac96666d06ec98d28e3f7346ddad287/libstdc%2B%2B-v3/include/bits/stl_vector.h#L524-L539)将预先分配内存.因此,您不会得到一堆不必要的重新分配,但您将通过容器获得额外的迭代 (3认同)