2015年5月22日金曜日

vector_array_for(C++)

配列、vectorforについて整理

配列中の要素を変更するには、参照を取得すること。

//
// 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;
}

0 件のコメント:

コメントを投稿