#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {7, 5, 6, 3, 2, 9, 0};
v.push_back(44);
v.push_back(129); // 尾部插入新元素
v.pop_back(); // 删除v尾部元素
// 检查v中是否有元素,v为空时返回true,v为非空时返回false
cout << "v.empty() = " << v.empty() << endl;
// 返回v中的元素个数
cout << "v.size() = " << v.size() << endl;
// 返回v中的第一个元素
cout << "v.front() = " << v.front() << endl;
// 返回v中的最后一个元素
cout << "v.back() = " << v.back() << endl;
// 遍历v中的所有元素
for(int n : v) {
cout << "n = " << n << endl;
}
cout << "===============1===============\n";
// 赋值运算和move()
vector<int> v1;
v1 = v;
for(int n1: v1) {
cout << "n1 = " << n1 << endl;
}
cout << "===============2===============\n";
vector<int> v2;
v2 = move(v);
// move()后,原始v中的数据被移动到v2中,v中已无元素
cout << "v.size() = " << v.size() << endl;
for(int n2: v2) {
cout << "n2 = " << n2 << endl;
}
cout << "===============3===============\n";
// 访问元素
vector<int> d = {5, 2, 1, 0, 8, 9};
// 修改d[1]的值
d.at(1) = 666;
for(int e : d) {
cout << "e = " << e << endl;
}
// 索引超过范围,抛出out of range异常
try {
d.at(10) = 999;
}
catch (out_of_range const& exec){
cout << exec.what() << endl;
}
// 赋值d1
vector<int> d1;
d1.assign(9, 5); // d1 = {5, 5, 5, 5, 5, 5, 5, 5, 5}
for(int e1 : d1) {
cout << "e1 = " << e1 << endl;
}
cout << "===============4===============\n";
d1.assign({1, 2, 3, 4, 5});
for(int e1 : d1) {
cout << "e1 = " << e1 << endl;
}
cout << "===============5===============\n";
// 迭代器begin()和end()
for(vector<int>::const_iterator iter = d.begin(); iter != d.end(); iter++) {
cout << "e2 = " << *iter << endl;
}
cout << "===============6===============\n";
// 迭代器rbegin()和rend()
for(vector<int>::reverse_iterator iter = d.rbegin(); iter != d.rend(); iter++) {
cout << "e2 = " << *iter << endl;
}
// capacity():返回d中元素个数
cout << "===============7===============\n";
cout << "d.capacity() = " << d.capacity() << endl;
// clear():清除d中的内容
cout << "===============8===============\n";
d.clear();
cout << "d.size() = " << d.size() << endl;
// insert():插入元素
cout << "===============9===============\n";
for(int n2: v2) {
cout << "n2 = " << n2 << endl;
}
return 0;
}
网友评论