将C数组附加到向量(在C++ 98/03中)非常简单,如下所示:
std::vector<int> vec;
const int array[5] = { 1 , 2 , 3 , 4 , 5};
vec.insert( vec.end() , array , array + 5 );
在C++98/03中,有没有一种方法可以在不编写for循环的情况下以相反的顺序将数组追加到向量中。( Sean Parent在这里看你。)
发布于 2017-08-16 18:30:45
这就对了。使用带有std::back_inserter
的std::reverse_copy
向向量添加元素:
std::vector<int> vec;
int array[5] = { 1 , 2 , 3 , 4 , 5};
std::reverse_copy(array , array + 5, std::back_inserter(vec));
如果你关心的是性能,不要忘了在复制之前使用reserve()
。
发布于 2017-08-16 18:28:21
vec.insert(std::end(vec),
std::rbegin(array),
std::rend(array));
请注意,这使用了C++14,但反向迭代器已经存在了很长时间,如果坚持使用较旧的标准,您只需手动创建它们:
int const a1[] = {1, 2, 3, 4, 5};
int a2[5];
std::copy(std::reverse_iterator<int const*>(std::end(a1)),
std::reverse_iterator<int const*>(std::begin(a1)),
std::begin(a2)); // copy in reverse
std::copy(std::begin(a2),
std::end(a2),
std::ostream_iterator<int>(std::cout, " ")); // prints "5 4 3 2 1 "
https://stackoverflow.com/questions/45711059
复制相似问题