Home » Community » Newbie corner » Multiply a scalar to every element of a vector
|
Re: Multiply a scalar to every element of a vector [message #56483 is a reply to message #56481] |
Wed, 17 March 2021 09:31 |
Oblivion
Messages: 1092 Registered: August 2007
|
Senior Contributor |
|
|
Hello David,
Something like this, maybe?
CONSOLE_APP_MAIN
{
StdLogSetup(LOG_COUT);
Vector<int> v = MakeIota(100, 1, 1);
// With for_each loop
std::for_each(v.begin(), v.end(), [](int& i) { i *= 10; });
RDUMP(v);
// With std::transform:
std::transform(v.begin(), v.end(), v.begin(), [](int i) { return i *= 10; });
RDUMP(v);
Vector<int> q;
std::for_each(v.begin(), v.end(), [&q](int i) { q.Add() = i /= 10; });
RDUMP(q);
}
Output:
v = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800, 810, 820, 830, 840, 850, 860, 870, 880, 890, 900, 910, 920, 930, 940, 950, 960, 970, 980, 990]
q = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Usually you can use U++ containers with basic std:: algorithms.
Best regards,
Oblivion
Github page: https://github.com/ismail-yilmaz
upp-components: https://github.com/ismail-yilmaz/upp-components
Bobcat the terminal emulator: https://github.com/ismail-yilmaz/Bobcat
[Updated on: Wed, 17 March 2021 10:17] Report message to a moderator
|
|
|
Goto Forum:
Current Time: Tue Apr 23 19:11:59 CEST 2024
Total time taken to generate the page: 0.01403 seconds
|