Last active
August 29, 2015 14:21
-
-
Save MasazI/d221f534f046a5dcf53a to your computer and use it in GitHub Desktop.
vector_array_for.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
| // | |
| // vector_for.cpp | |
| // CplusplusPractice | |
| // | |
| // Created by masai on 2015/05/22. | |
| // Copyright (c) 2015年 masai. All rights reserved. | |
| // | |
| #include <iostream> | |
| #include <vector> | |
| using namespace std; | |
| int main(int argc, char* argv[]){ | |
| vector<int> v(5); | |
| fill(v.begin(), v.end(), 10); | |
| // intのベクターをautoで取り出す | |
| cout << "int auto" << endl; | |
| for(auto a : v){ | |
| cout << a << endl; | |
| } | |
| // intのベクターをauto&で取り出しても同じ結果 | |
| cout << "int auto&" << endl; | |
| for(auto& a : v){ | |
| cout << a << endl; | |
| } | |
| vector<string> v_str(5); | |
| fill(v_str.begin(), v_str.end(), "abc"); | |
| // stringのベクターをautoで取り出しても読み出し可能だが、実体は変更できない | |
| cout << "string auto" << endl; | |
| for(auto b : v_str){ | |
| b = "change"; | |
| cout << b << endl; | |
| } | |
| cout << v_str[0] << endl; | |
| // stringのベクターをauto&で取りだすと、配列内のstringの実体を変更できる | |
| cout << "string auto&" << endl; | |
| for(auto& b : v_str){ | |
| b = "change;"; | |
| cout << b << endl; | |
| } | |
| cout << v_str[0] << endl; | |
| // vectorの配列ではどうか | |
| vector<string> v_str1(2); | |
| fill(v_str1.begin(), v_str1.end(), "abc1"); | |
| vector<string> v_str2(2); | |
| fill(v_str2.begin(), v_str2.end(), "abc2"); | |
| vector<string> v_str3(2); | |
| fill(v_str3.begin(), v_str3.end(), "abc3"); | |
| vector<string> v_array[3] = {v_str1, v_str2, v_str3}; | |
| // 配列からベクターをautoで取り出すと、&を付けないと実体が異なる | |
| for(auto vs : v_array){ | |
| vs.resize(5); | |
| cout << vs.size() << endl; | |
| } | |
| cout << v_array[0].size() << endl; | |
| // 配列からベクターをauto&で取り出すと、配列内のvectorの実体を変更できる | |
| for(auto& vs : v_array){ | |
| vs.resize(7); | |
| cout << vs.size() << endl; | |
| } | |
| cout << v_array[0].size() << endl; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment