当前位置:首页 > 通信资讯 > 正文

c++ vector的实现(c++中vector的用法详解)

  下面随笔讲解c++ vector对象。

vector对象

  为什么需要vector?

  • 封装任何类型的动态数组,自动创建和删除。
  • 数组下标越界检查。
  • 封装的如ArrayOfPoints也提供了类似功能,但只适用于一种类型的数组。

vector对象的定义

vector<元素类型>数组对象名(数组长度);

例:

    vector<int> arr(5)
    建立大小为5的int数组

vector对象的使用

对数组元素的引用

与普通数组具有相同形式:

vector对象名[下标表达式]

vector数组对象名不表示数组首地址

  • 获得数组长度
  • 用size函数

数组对象名.size()

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 //例 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; }
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 //基于范围的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; }

以上就是c++ vector对象相关总结的详细内容,更多关于c++ vector对象的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/iFrank/p/14446990.html

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。