下面随笔讲解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; }
以上就是c++ vector对象相关总结的详细内容,更多关于c++ vector对象的资料请关注呐喊教程其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。