将列表转换为 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/