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?
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?
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;
}