vector容器(上)
一、基本概念
(1)vector数据结构和数组非常相似,也称为单端数组;;
(2)vector容器可以动态扩展(并不是在原空间之后续接新空间,而是找更大的内存空间,然后将原数据拷贝新空间,释放原空间;
二、构造函数
(1)函数原型:
①vector<T> v;//采用模板实现类实现,默认构造函数;
②vector(n,elem); //构造函数将n个elem拷贝给本身;
③vector(const vector &vec) //拷贝构造函数
1 #include <iostream> 2 using namespace std; 3 #include <vector> 4 void printVector(vector<int>& v) //打印容器中的元素 5 { 6 for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) 7 { 8 cout << *it << " "; 9 } 10 cout << endl; 11 } 12 void test01() 13 { 14 vector<int> v1; 15 for (int i = 0; i < 10; i++) 16 { 17 v1.push_back(i); 18 } 19 printVector(v1); 20 21 vector<int>v2(v1.begin(), v1.end()); //拷贝构造函数,将v1中的元素拷贝到v2 22 printVector(v2); 23 24 vector<int> v3(10, 100); //用n个elem给v3赋值 25 printVector(v3); 26 27 vector<int> v4(v3); //将v3拷贝给v4 28 printVector(v4); 29 } 30 int main() 31 { 32 test01(); 33 return 0; 34 35 }
运行结果:
三、vector赋值操作
(1)功能描述: 给vector容器进行赋值;
(2)函数原型:
①vector& operator=(const vector &vec)//即直接用等号赋值
②assign(beg,end); //将【beg,end)区间中的数据拷贝赋值给本身
③assign(n,elem); //将n个elem拷贝赋值给本身;
1 #include <iostream> 2 using namespace std; 3 #include <vector> 4 void printVector(vector<int>& v) 5 { 6 for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) 7 { 8 cout << *it << " "; 9 } 10 cout << endl; 11 } 12 void test01() 13 { 14 vector<int>v1; //无参构造 15 for (int i = 0; i < 10; i++) 16 { 17 v1.push_back(i); 18 } 19 printVector(v1); 20 21 vector<int>v2; 22 v2 = v1; //用等号赋值 23 printVector(v2); 24 25 vector<int>v3; 26 v3.assign(v1.begin(), v1.end()); 27 printVector(v3); 28 29 vector<int>v4; 30 v4.assign(10, 100); 31 printVector(v4); 32 } 33 int main() 34 { 35 test01(); 36 return 0; 37 }
运行结果:

四、vector容量和大小
(1)功能描述:对vector容器的容量和大小操作;
(2)函数原型:
①empty(); //判断容器是否为空
②capacity(); //容器的容量
③size(); //返回容器中元素的个数
④resize(int num); //重新指定容器的长度为num,若容器变长,则以默认值填充新位置,如果容器变短,则容器末尾超过容器长度的元素将会被删除;
resize(int num ,elem); //重新指定容器的长度为num,若容器变长,则以elem值填充新位置
1 #include <iostream> 2 using namespace std; 3 #include <vector> 4 void printVector(vector<int>& v) 5 { 6 for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) 7 { 8 cout << *it << " "; 9 } 10 cout << endl; 11 } 12 void test01() 13 { 14 vector<int>v1; 15 for (int i = 0; i < 10; i++) 16 { 17 v1.push_back(i); 18 } 19 printVector(v1); 20 if (v1.empty()) 21 { 22 cout << "容器为空" << endl; 23 } 24 else 25 { 26 cout << "容器不为空" << endl; 27 cout << "v1的容量:" << v1.capacity() << endl; 28 cout << "v1的大小:" << v1.size() << endl; 29 } 30 v1.resize(20, 10); //resize重新指定大小,若指定的更大,默认用0填充新位置,可以利用重载版本替代默认值 31 printVector(v1); 32 33 v1.resize(5); //重新指定大小,若指定的更小,超出部分元素被删除 34 printVector(v1); 35 } 36 int main() 37 { 38 test01(); 39 return 0; 40 }
运行结果:

浙公网安备 33010602011771号