繁体   English   中英

如何使用迭代器在向量中的不同位置插入多个元素?

[英]How to insert multiple elements in the vector at different positions using iterator?

我想编写一个将向量[2, 1, 4, 0, 5]更改为的函数

[2, 2, 1, 4, 4, 4, 4, 5, 5, 5, 5, 5]

我可以通过将向量弹出到数组中,然后将元素推回向量中来实现。

我如何使用插入来做到这一点? 我可以修改以下程序吗? 最有效的方法是什么?

void timesDuplicates(vector<int>& a) 
{
    int s = a.size(), count = 0;
    for(int i = 0; count < s ; i+=a[i], count++) {
        if(a[i] == 0) continue;
        a.insert(a.begin()+i, a[i], a[i]); 
    }
}

我如何使用插入来做到这一点? 我可以修改以下程序吗?

关于效率,向量在插入时每次都会经过几次重新分配,因为在提供的代码中, std :: vector :: reserved没有存储任何内存,即使它可以通过汇总元素来完成。 就像@IgorTandetnik指出的那样,也无法转换传递的向量。

最简单的方法是,创建一个新的向量,其中仅根据传递的向量中存在的元素数目, 将std :: vector :: insert元素插入其中。

以下是示例代码。 请参见直播

#include <iostream>
#include <vector>
#include <numeric>  // std::accumulate

std::vector<int> timesDuplicates(const std::vector<int>& vec)
{
    std::vector<int> result;
    // reserve the amount of memory for unwanted reallocations
    result.reserve(std::accumulate(std::cbegin(vec), std::cend(vec), 0));
    // you do not need to check element == 0 here
    // as std::vector::insert(end, 0, 0) will insert nothing
    for (const int element : vec) result.insert(result.end(), element, element);
    // return the result
    return result;
}

int main()
{
    const auto result{ timesDuplicates({ 2, 1, 4, 0, 5 }) };
    for (const int ele : result) std::cout << ele << " ";
    return 0;
}

或者,如果您不相信NRVO或复制省略的发生,请在保留所需的内存后将向量result作为参数( ref )传递给函数。

#include <iostream>
#include <vector>
#include <numeric>  // std::accumulate

void timesDuplicates(
    const std::vector<int>& vec,
          std::vector<int>& result)
{
    for (const int element : vec)
        result.insert(result.end(), element, element);
}

int main()
{
    const std::vector<int> vec{ 2, 1, 4, 0, 5 };
    std::vector<int> result;
    result.reserve(std::accumulate(std::cbegin(vec), std::cend(vec), 0));
    timesDuplicates(vec, result);
    for (const int ele : result) std::cout << ele << " ";
    return 0;
}

尝试递归使用此代码段。 由于您正在弹出并推入新的临时向量,因此push_back就足够了(insert将要求您找到新的插入位置)

void timesDuplicates(vector<int>& vec, int idx = 0)
{
    static vector<int> result;    
    int v = vec[idx];              // get value
    for (int i = 0; i < v; i++)    // multiply value
    {
        result.push_back(v);   // push value to temp vector (result)
    }    
    if (idx == vec.size() - 1) {   // border condition
        vec.swap(result);      // swap result
        return;                
    }    
    timesDuplicates(vec, ++idx);   // increment index   
}

void main()
{
    vector<int> vec = { 2, 1, 4, 0, 5 };
    timesDuplicates(vec);
    for (auto e : vec)
        cout << e << " ";
    cout << "\n";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM