primer_C++_3.5 数组
/* * 定义一个10个Int的数组,令每个元素的值就是其下标 */ #include <iostream> using namespace std; int main() { constexpr size_t array_size = 10; int a1[array_size]; int a = 0; for (size_t i=0; i< array_size; i++) { a1[i] = i ; } for (auto i : a1) cout<< i<<" "; return 0; }
#include <iostream> using namespace std; int main() { constexpr size_t array_size = 10; int a1[array_size]; int b1[array_size]; int a = 0; for (size_t i=0; i< array_size; i++) a1[i] = i ; for (size_t i = 0; i < array_size; i++) b1[i] = a1[i]; for (auto i : a1) cout<< i<<" "; cout << endl; for (auto i : b1) cout << i << " "; return 0; }
#include <iostream> #include <string> #include <vector> using namespace std; void main() { int a[10] = { 0,1,2,3,4,5,6,7,8,9 }; vector<int> v1(begin(a),end(a)); vector<int> v2 = v1; for (auto i : v1) cout << i<<" "; cout << endl; for (auto i : v2) cout << i; }
/* * 编写一段程序,利用指针将数组中的元素为0 */ #include <iostream> using namespace std; int main() { int a[5] = { 1,2,3,4,5 }; cout << "原数据:"; for (auto i : a) cout << i; cout << endl; int *pbeg =begin(a),*pend = end(a); while (pbeg != pend && *pbeg >= 0) { *pbeg = 0; ++pbeg; } cout << "修改后:"; for (auto i : a) cout << i; return 0; }
/* * 判断两个数组中的元素是否相等 */ #include <iostream> #include <string> #include <vector> using namespace std; void main() { int a[10] = { 0,1,2,3,4,5,6,7,8,9 }; int b[10] = { 0,1,2,3,4,5,6,7,8,9 }; int count = 0; if (sizeof(a) == sizeof(b)){ for (int i = 0; i < 10; i++){ if (a[i] == b[i]){ count++; } } } if (count == 10){ cout << "Equal" << endl; }else{ cout << "Not Equal" << endl; } }
vector
/* * 判断两个数组中的元素是否相等 */ #include <iostream> #include <string> #include <vector> using namespace std; void main() { int a[10] = { 0,0,2,3,4,5,6,7,8,9 }; int b[10] = { 0,1,2,3,4,5,6,7,8,9 }; vector<int> v1(begin(a),end(a)); vector<int> v2(begin(b), end(b)); if (v1 == v2){ cout << "Equal" << endl; }else{ cout << "Not Equal" << endl; } }
#include <iostream> #include <string> #include <vector> using namespace std; void main() { char a[100] = "Hello World"; char b[100] = "I want peace"; char c[200]; strcpy(c, a); strcat(c, " "); strcat(c, b); cout << c; }
#include <iostream> #include <vector> using namespace std; int main() { int arry[5] = { 1, 2, 3, 4,5 }; vector<int> v1(arry , arry+5); for (auto i : v1) cout << i; return 0; }
#include <iostream> #include <vector> using namespace std; int main() { int arry[10] ; vector<int> v1(10 , 1); for (int i = 0; i < 10; i++) { arry[i] = v1[i]; cout << arry[i]<<" "; } return 0; }