dimanche 30 juin 2019

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

I want to write a function that changes the vector [2, 1, 4, 0, 5] to

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

I could do it by popping the vector into an array and then pushing the elements back to the vector.

How can I use insert to do it? Can I modify the following program? What is the most efficient way?

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]); 
    }
}

Aucun commentaire:

Enregistrer un commentaire