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

标签 c++ c++11 c++17

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

我在想一个循环。但也许 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);
}

在 C# 中,我可以使用接受 IEnumerable 接口(interface)的构造函数来初始化其他数据类型。很好奇 C++11 是否支持任何类似的东西......

最佳答案

std::vector 的构造函数之一(实际上,对于任何标准容器),采用一对迭代器:

template< class InputIt >
vector( InputIt first, InputIt last, 
        const Allocator& alloc = Allocator() );

所以你可以这样做:

vector<string> v(list_string.begin(), list_string.end());

关于c++ - 将 STL list<string> 转换为 vector<string> c++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51052961/

相关文章:

c++ - 命名空间 'size' 中没有名为 'std' 的成员

c++ - 使用 Qt5 从 USB 摄像头录制视频

c++ - 用户定义类型的 static_cast

c++ - 为什么相同的模板类会得到相同的静态 ID?

c++ - 所有 C++ 代码(完全相同)在 Windows 系统和基于 Linux 的系统上编译和工作是否相同?为什么?[用 c++] [RBIx]

c++ - move 语义和 std::future

c++ - 带有对象的初始化列表是不可移植的?

c++ - std::array:size和max_size返回相同的数字(如果array中的元素较少)

c++ - 强制列表初始化矩阵的大小

c++ - 将 std::vector<std::string> 转换为 const char* const*