#2
by かずま » 8年前
time2() をイテレータを使って書くと times2c() になります。
コード:
#include <iostream>
#include <vector>
std::vector<int> times2(const std::vector<int>& vec) {
std::vector<int> tmp(vec);
for (auto& x: tmp) {x *= 2;} // x は、times2c の x と同じ
return tmp;
}
std::vector<int> times2c(const std::vector<int>& vec) {
std::vector<int> tmp(vec); // copy ctor
for (auto it = tmp.begin(); it != tmp.end(); ++it) {
auto& x = *it; // x は、tmp[0], tmp[1], ... への参照
x *= 2; // time[0], time[1], ... が 全部 2倍になる
}
return tmp;
}
std::vector<int> times2d(const std::vector<int>& vec) {
std::vector<int> tmp(vec);
for (auto x: tmp) {x *= 2;} // & がないと、times2e() の x と同じ
return tmp;
}
std::vector<int> times2e(const std::vector<int>& vec) {
std::vector<int> tmp(vec); // tmp は vec のコピー
for (auto it = tmp.begin(); it != tmp.end(); ++it) {
auto x = *it; // x はローカル変数 (tmp[0], ... のコピー)
x *= 2; // x を変更しても tmp[0], ... は変更されない
}
return tmp; // vec と同じ内容の vector を返す
}
int main()
{
std::vector<int> a = { 1, 2, 3, 4, 5 };
std::vector<int> b = times2(a);
for (auto&x : b) std::cout << " " << x;
std::cout << std::endl;
std::vector<int> c = times2c(a);
for (auto it = c.begin(); it != c.end(); ++it) std::cout << " " << *it;
std::cout << std::endl;
std::vector<int> d = times2d(a);
for (auto i = 0; i < d.size(); ++i) std::cout << " " << d[i];
std::cout << std::endl;
}
実行結果
コード:
2 4 6 8 10
2 4 6 8 10
1 2 3 4 5
time2() をイテレータを使って書くと times2c() になります。
[code]
#include <iostream>
#include <vector>
std::vector<int> times2(const std::vector<int>& vec) {
std::vector<int> tmp(vec);
for (auto& x: tmp) {x *= 2;} // x は、times2c の x と同じ
return tmp;
}
std::vector<int> times2c(const std::vector<int>& vec) {
std::vector<int> tmp(vec); // copy ctor
for (auto it = tmp.begin(); it != tmp.end(); ++it) {
auto& x = *it; // x は、tmp[0], tmp[1], ... への参照
x *= 2; // time[0], time[1], ... が 全部 2倍になる
}
return tmp;
}
std::vector<int> times2d(const std::vector<int>& vec) {
std::vector<int> tmp(vec);
for (auto x: tmp) {x *= 2;} // & がないと、times2e() の x と同じ
return tmp;
}
std::vector<int> times2e(const std::vector<int>& vec) {
std::vector<int> tmp(vec); // tmp は vec のコピー
for (auto it = tmp.begin(); it != tmp.end(); ++it) {
auto x = *it; // x はローカル変数 (tmp[0], ... のコピー)
x *= 2; // x を変更しても tmp[0], ... は変更されない
}
return tmp; // vec と同じ内容の vector を返す
}
int main()
{
std::vector<int> a = { 1, 2, 3, 4, 5 };
std::vector<int> b = times2(a);
for (auto&x : b) std::cout << " " << x;
std::cout << std::endl;
std::vector<int> c = times2c(a);
for (auto it = c.begin(); it != c.end(); ++it) std::cout << " " << *it;
std::cout << std::endl;
std::vector<int> d = times2d(a);
for (auto i = 0; i < d.size(); ++i) std::cout << " " << d[i];
std::cout << std::endl;
}
[/code]
実行結果
[code=text]
2 4 6 8 10
2 4 6 8 10
1 2 3 4 5
[/code]