どうも、ちょげ(@chogetarou)です。
リスト(List)の全要素に特定の値を掛け算する方法を紹介します。
方法

リスト(List)の全要素に特定の値を掛け算する方法は、2つあります。
for文
ひとつは、for文を使う方法です。
まず、for文でリストをループします。
そして、ループ処理で、リストの要素に「*」で値を掛けます。
//myList=対象のリスト, value=値
for (auto it = myList.begin(); it != myList.end(); ++it) {
*it *= value;
}
上記のfor文は、リストの全要素に特定の値を掛け算します。
使用例
#include <iostream>
#include <list>
using namespace std;
int main(void){
list<int> nums = { 11, 2, 8, 20, 7, 4 };
int value = 10;
for (auto it = nums.begin(); it != nums.end(); ++it) {
*it *= value;
}
for(int item: nums) {
cout << item << endl;
}
return 0;
}
出力:
110
20
80
200
70
40
for_each()
もうひとつは、for_each()を使う方法です。
まず、algorithmをインクルードします。
#include <algorithm>
次に、for_each()を呼び出します。
for_each()の第1引数にリストのイテレータの先頭、第2引数にリストのイテレータの末尾を指定します。
for_each()の第3引数に、引数で要素の参照を受け取る関数を指定します。
そして、関数の処理で、引数に「*」で値を掛けます。
//myList=対象のリスト, T=要素の型, value=足す値
for_each(myList.begin(), myList.end(), [](T& item) { item *= value; });
上記のfor_each()は、リストの全要素に特定の値を掛け算します。
使用例
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main(void){
list<int> nums = { 11, 2, 8, 20, 7, 4 };
for_each(nums.begin(), nums.end(), [](int& item) { item *= 100; });
for(int item: nums) {
cout << item << endl;
}
return 0;
}
出力:
1100
200
800
2000
700
400
まとめ
リスト(List)の全要素に特定の値を掛け算する方法は、次の2つです。
- for文を使う方法
for (auto it = myList.begin(); it != myList.end(); ++it) { *it *= value; }
- for_each()を使う方法
for_each(myList.begin(), myList.end(), [](T& item) { item *= value; });
コメント