【问题标题】:Repeat elements in a vector重复向量中的元素
【发布时间】:2018-09-30 00:06:36
【问题描述】:

我有一个向量

vector<int>v = {1,2,3,4,5};

我想将向量中的元素重复 3 次,这样向量就变成了

v = {1,2,3,4,5, 1,2,3,4,5, 1,2,3,4,5};

编辑:事实上,如果我需要多次重复元素,比如 1000 次,显然我必须提供一些快速而轻松的东西?

我该怎么做?

【问题讨论】:

标签: c++ vector


【解决方案1】:

使用vector类的insert方法

v.insert(v.end(), v.begin(), v.end());

【讨论】:

  • 事先使用v.reserve(3 * v.size());(迭代器失效)。如果你想重复两次,你必须记住旧的结局。
  • 似乎只重复元素两次?
【解决方案2】:

使用std::copy

std::vector<int> v = { 1 , 2, 3, 4, 5};
std::vector<int> r;

for (auto i = 0; i < 3; ++i) {
    std::copy(v.begin(), v.end(), std::back_inserter(r));
}
v.swap(r);

【讨论】:

【解决方案3】:

这可能很棘手。如果您想避免创建临时工作对象,则必须小心避免在进行时使迭代器无效。应该这样做:

std::vector<int> v = {1, 2, 3, 4, 5};

// to avoid invalidating iterators, preallocate the memory
v.reserve(v.size() * 3);

// remember the end of the range to be duplicated
// (this is the iterator we don't want to invalidate)
auto end = std::end(v);

// insert two duplicates
v.insert(std::end(v), std::begin(v), end);
v.insert(std::end(v), std::begin(v), end);

for(auto i: v)
    std::cout << i << '\n';

更一般地,您可以修改它以添加多个重复项,如下所示:

std::vector<int> v = {1, 2, 3, 4, 5};

std::size_t const no_of_duplicates = 1000;

// to avoid invalidating iterators, preallocate the memory
v.reserve(v.size() * no_of_duplicates);

// remember the end of the range to be duplicated
// (this is the iterator we don't want to invalidate)
auto end = std::end(v);

// insert duplicates (start from one because already have the first)
for(std::size_t i = 1; i < no_of_duplicates; ++i)
    v.insert(std::end(v), std::begin(v), end);

【讨论】:

    猜你喜欢
    • 2014-11-21
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多