Multiply a vector with scalar with ranges in c++20
- User
Multiply a vector with scalar with ranges in c++20
- Assistant
In C++20, you can use the ranges library to easily multiply a vector with a scalar. Here's an example code:
#include <iostream> #include <vector> #include <ranges> int main() { std::vector<int> v{1, 2, 3, 4, 5}; int scalar = 10; auto new_v = v | std::views::transform([scalar](int x){ return x * scalar; }); for (auto x : new_v) { std::cout << x << " "; } std::cout << std::endl; return 0; }In this code, we have a vector
vand a scalarscalar. We use thestd::views::transformfunction from the ranges library to create a new view of the vector where each element is multiplied by the scalar. Note that we passed the lambda function[scalar](int x){ return x * scalar; }tostd::views::transform, which takes an integerxand multiplies it by the scalarscalar.Finally, we iterate over the new view of the vector and print out each element. The output of the program is:
10 20 30 40 50 - User
can I not use ranges and transform?
- Assistant
Yes, you can also multiply a vector with a scalar without using ranges and transform. Here's an example code:
#include <iostream> #include <vector> int main() { std::vector<int> v{1, 2, 3, 4, 5}; int scalar = 10; for (auto& x : v) { x = x * scalar; } for (auto x : v) { std::cout << x << " "; } std::cout << std::endl; return 0; }In this code, we have a vector
vand a scalarscalar. We use a for loop to iterate over each element of the vector and multiply it by the scalar. Note that we used a reference toxin the loop (auto& x) so that we can modify the element in place.Finally, we iterate over the modified vector and print out each element. The output of the program is:
10 20 30 40 50 - User
make it use ranges and transform
- Assistant
Sure, here's the same code using the ranges library and transform:
#include <iostream> #include <vector> #include <ranges> int main() { std::vector<int> v{1, 2, 3, 4, 5}; int scalar = 10; std::ranges::transform(v, v.begin(), [scalar](int x) { return x * scalar; }); for (const auto& x : v) { std::cout << x << " "; } std::cout << std::endl; return 0; }In this code, we use the
std::ranges::transformalgorithm from the ranges library to transform the original vectorvand assign the result to a new vector that starts atv.begin(). We passed the lambda function[scalar](int x) { return x * scalar; }tostd::ranges::transform, which takes an integerxand multiplies it by the scalarscalar. Note that we usedconst auto& xin the second loop to avoid making a copy of each element.Finally, we iterate over the modified vector and print out each element. The output of the program is:
10 20 30 40 50