<C++ Primer_5th>习题_3.31

来源:互联网 发布:ubuntu修改hosts翻墙 编辑:程序博客网 时间:2024/06/06 03:55
//编写一个程序,定义一个含有10个int的数组,令每个元素的值就是其所在位置的值#include<iostream>using namespace std;int main(){const int sz = 10;int a[sz];//遍历数组元素并赋值for (int i = 0; i < sz; ++i){a[i] = i;}//输出数组中的全部元素cout << "数组中的元素依次为:";for (auto c : a){cout <<c << "  ";}cout << endl;system("pause");return 0;}//将上面创建的数组拷贝给另外一个数组。利用vector重写程序,实现类似功能//利用数组来拷贝#include<iostream>using namespace std;int main(){const int sz = 10;int a[sz], b[sz];//利用for循环为数组赋值for (int i = 0; i < sz; ++i)a[i] = i;for (int j = 0; j < sz; ++j)b[j] = a[j];//利用范围for循环输出数组的全部元素cout << "数组中的元素依次为: ";for (auto c : b)cout << c << "  ";cout << endl;system("pause");return 0;}//利用vector实现拷贝#include<iostream>#include<vector>using namespace std;int main(){const int sz = 10;vector<int> v_int, v_int2;for (int i = 0; i < sz; ++i)v_int.push_back(i);for (int j = 0; j < sz; ++j)v_int2.push_back(v_int[j]);//输出vector对象中的元素cout << "输出的元素依次为: ";for (auto c : v_int2)cout << c << "  ";cout << endl;system("pause");return 0;}