0

How would you code list multiplying with a scale in c++?

In python I would do:

lst = [1,2,3]
lst*3 # we will get [1,2,3,1,2,3,1,2,3]

What is the c++ equivalent of that?

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
Albert G Lieu
  • 891
  • 8
  • 16
  • 1
    There's nothing built-in. But you can use vector concatenation repeatedly. See https://stackoverflow.com/questions/201718/concatenating-two-stdvectors – Barmar Dec 14 '21 at 01:04

1 Answers1

1

If you really need the operation of multiplication, for example, you are developing some math library, you can consider the operator overloading. Otherwise, I suggest you throwing the python style away while working with C++, just use std::copy or vector::insert with a loop to insert repeated elements into a vector.

std::vector<int>& operator*(std::vector<int>& vec, std::size_t n) {
    auto initSize = vec.size();
    for (std::size_t i = 0; i < n - 1; ++i) {
        vec.insert(vec.end(), vec.begin() + initSize * i, vec.end());
    }
    return vec;
}

// commutative principle for multiplication
std::vector<int>& operator*(std::size_t n, std::vector<int>& vec) {
    return operator*(vec, n);
}

int main()
{
    std::vector<int> vec {1, 2, 3};
    vec = vec * 3; // 3 * vec is OK too

    for (auto val : vec) {
        std::cout << val << ' ';
    }

    return 0;
}
Yves
  • 11,597
  • 17
  • 83
  • 180
  • I'd really discourage this as it is not clear what `vec * 3` means to an average programmer. My first guess would be element-wise vector multiplication. Doing this causes much ambiguity. A much better option is to just create a named function instead and call it: `vec = repeat(vec, 3)`. – Ted Klein Bergman Dec 14 '21 at 02:07
  • @TedKleinBergman I agree with you. – Yves Dec 14 '21 at 02:08
  • It’s just not that common. If you find it common, write a function that takes a sequence and appends n times. (There may be a C++20 ranges one-liner…) – Ben Dec 14 '21 at 02:10
  • @Ben C++ committee has all kinds of experts with very different background, it's kind of hard to say "it's just not that common". With my technique background, I would say: we should totally remove the operator overloading from the C++ Standard. – Yves Dec 14 '21 at 02:13
  • Ok. I think the generic algorithm you may want is `template OutIter copy_n_times(const Range&, OutIter out, std::size_t n) { OutIter result = out; for (std::size_t i = 0; i != n; ++i) { result = std::copy(range.begin(); range.end(), result); } return result; }` – Ben Dec 14 '21 at 03:15