Created
May 22, 2015 07:23
-
-
Save MasazI/cd023523510f28f563b6 to your computer and use it in GitHub Desktop.
transform.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // transform.cpp | |
| // CplusplusPractice | |
| // | |
| // Created by masai on 2015/05/22. | |
| // Copyright (c) 2015年 masai. All rights reserved. | |
| // | |
| #include <iostream> | |
| #include <vector> | |
| using namespace std; | |
| // 関数オブジェクトで記述するため構造体 | |
| struct FunctionObject{ | |
| int operator()(int value){ | |
| return value * 2; | |
| } | |
| }; | |
| int main(int argc, char* argv[]){ | |
| vector<int> v(3); | |
| fill(v.begin(), v.end(), 1); | |
| for(int i : v){ | |
| cout << i << endl; | |
| } | |
| // 関数オブジェクトで変換を記述 | |
| transform(v.begin(), v.end(), v.begin(), FunctionObject()); | |
| for(int i : v){ | |
| cout << i << endl; | |
| } | |
| // ラムダ式で変換を記述 []の中は処理する値を参照で受け取るかどうかを記述する。空の場合は値渡し、&で参照渡しとなる。今回はプリミティブ型なので空でも処理はうまくいく。 | |
| transform(v.begin(), v.end(), v.begin(), [&](int x) { return x * 10; }); | |
| for(int i : v){ | |
| cout << i << endl; | |
| } | |
| // 別のベクトルに入れる場合 | |
| vector<int> v2(v.size()); | |
| transform(v.begin(), v.end(), v2.begin(), [&](int x) { return x * 100; }); | |
| for(int i : v2){ | |
| cout << i << endl; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment