时间:2022-07-06 10:17:16 | 栏目:C代码 | 点击:次
下面随笔讲解c++ vector对象。
为什么需要vector?
vector<元素类型> 数组对象名(数组长度);
例:
vector<int> arr(5)
建立大小为5的int数组
与普通数组具有相同形式:
vector数组对象名不表示数组首地址
数组对象名.size()
//例 vector应用举例 #include <iostream> #include <vector> using namespace std; //计算数组arr中元素的平均值 double average(const vector<double> &arr) { double sum = 0; for (unsigned i = 0; i<arr.size(); i++) sum += arr[i]; return sum / arr.size(); } int main() { unsigned n; cout << "n = "; cin >> n; vector<double> arr(n); //创建数组对象 cout << "Please input " << n << " real numbers:" << endl; for (unsigned i = 0; i < n; i++) cin >> arr[i]; cout << "Average = " << average(arr) << endl; return 0; }
//基于范围的for循环配合auto举例 #include <vector> #include <iostream> int main() { std::vector<int> v = {1,2,3}; for(auto i = v.begin(); i != v.end(); ++i) std::cout << *i << std::endl; for(auto e : v) std::cout << e << std::endl; }