首页上一页 1 下一页尾页 1 条记录 1/1页
vector实例结果与vs2019运行结果不同而且上面给的返回最多容量函数与下面实例中不同
发表在C++图书答疑
2022-05-09
《C++从入门到精通(第3版)》第13章 STL标准模板库 313页-315页
是否精华
是
否
版块置顶:
是
否
#include<iostream> #include<iomanip> #include<vector> #include<tchar.h> using namespace std; int main() { vector<int>v1, v2; v1.resize(10); //手动分配空间 cout << "v1容量" << v1.capacity() << endl; v2.resize(10); v1 = vector<int>(8, 7); int arrary[8] = { 1,2,3,4,5,6,7,8 }; v2 = vector<int>(arrary, arrary + 8); cout << "v1容量" << v1.capacity() << endl; cout << "v1当前各项:" << endl; for (decltype(v2.size())i = 0; i < v1.size(); i++) cout << setw(2) << v1[i]; cout << endl; cout << "v2容量" << v2.capacity() << endl; cout << "v2当前各项:" << endl; for (vector<int>::size_type i = 0; i < v1.size(); i++) cout << setw(2) << v2[i]; cout << endl; v1.resize(0); cout << "v1的容器通过resize函数变成0" << endl; if (!v1.empty()) cout << "v1容量" << v1.capacity() << endl; else cout<<"v1是空的"<<endl; cout << "将v1容量扩展为8" << endl; v1.resize(8); cout << "v1当前各项:" << endl; for (decltype(v1.size())i = 0; i < v1.size(); i++) cout << setw(2) << v1[i]; cout << endl; v1.swap(v2); cout << "v1与v2swap了" << endl; cout << "v1容量" << v1.capacity() << endl; cout << "v1当前各项:" << endl; for (decltype(v1.size())i = 0; i < v1.size(); i++) cout << setw(2) << v1[i]; cout << endl; v1.push_back(3); cout << "从v1后面加入了元素3" << endl; cout<<"v1容量:" << v1.capacity() << endl; for (decltype(v1.size())i = 0; i < v1.size(); i++) cout << setw(2) << v1[i]; cout << endl; v1.erase(v1.end()-2); cout << "删除了倒数第二个元素" << endl; cout << "v1容量" << v1.capacity() << endl; cout << "当前各项:" << endl; for (decltype(v1.size())i = 0; i < v1.size(); i++) cout << setw(2) << v1[i]; cout << endl; v1.pop_back(); cout << "通过栈操作pop_back释放最后的元素" << endl; cout << "v1当前各项:" << endl; cout << "v1容量" << v1.capacity() << endl; for (vector<int>::size_type i = 0; i < v1.size(); i++) cout << setw(2) << v1[i]; cout << endl; return 0; }//按照书上的敲