Montezuman
Montezuman

Reputation: 7

Adding elements to std::vector in a repeated way

I want to copy values from one vector to other one that will be stored in a specific order and the second vector will contain more elements than the first one.

For example:

vector<int> temp;
temp.push_back(2);
temp.push_back(0);
temp.push_back(1);
int size1 = temp.size();

int size2 = 4;
vector<int> temp2(size1 * size2);

And now I would like to fill temp2 like that: {2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1}.

Is it possible to do this using only algorithms (e.g. fill)?

Upvotes: 1

Views: 104

Answers (2)

Fureeish
Fureeish

Reputation: 13424

Yes, it is possible using std::generate_n algorithm:

int main() {
    std::vector<int> base{1, 0, 2};
    const int factor = 4;
    std::vector<int> out{};

    std::generate_n(std::back_inserter(out), base.size() * factor,
            [&base, counter=0]() mutable {
        return base[counter++ / factor];
    });

    for(const auto i : out) {
        std::cout << i << ' ';
    }
}

This code prints: 1 1 1 1 0 0 0 0 2 2 2 2

The key is the lambda used in std::generate_n. It operates on internal counter to know which values, based on base vector (and accessed depending on factor and counter values), to generate.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

No, this is quite a specific use case, but you can trivially implement it yourself.

#include <vector>
#include <iostream>

std::vector<int> Elongate(const std::vector<int>& src, const size_t factor)
{
    std::vector<int> result;
    result.reserve(src.size() * factor);

    for (const auto& el : src)
       result.insert(result.end(), factor, el);

    return result;
}

int main()
{
   std::vector<int> temp{2, 0, 1};
   std::vector<int> real = Elongate(temp, 4);

   for (const auto& el : real)
       std::cerr << el << ' ';
   std::cerr << '\n';
}

(live demo)

Upvotes: 1

Related Questions