C++ STL中vector容器的使用
目录
- 一、vector
- (1)区分size()和capacity()
- (2)迭代器失效
- (3)区分const_iterator和constiterator
- (4)区分reserve()和resize()
- (5)push_back和emplace
- (6)关于原位构造(定位new+完美转发)
- 总结
一、vector
(1)区分size()和capacity()
size()
:返回容纳的元素个数capacity()
:返回当前分配存储的容量
(2)迭代器失效
(3)区分const_iterator和const iterator
const_iterator
:常性迭代器,指向的对象的属性为常性;const iterator
:常性的普通迭代器,迭代器自身属性为常性;
(4)区分reserve()和resize()
reserve():预留存储空间,只改变capacity
增加 vector 的容量到大于或等于 new_cap 的值。若 new_cap 大于当前的 capacity() ,则分配新存储,否则该方法不做任何事。reserve() 不更改 vector 的 size 。
若 new_cap 大于 capacity() ,则所有迭代器,包含尾后迭代器和所有到元素的引用都被非法化。否则,没有迭代器或引用被非法化。
#include <iostream> #include <vector> using namespace std; class Value { public: Value() { cout << "Value()"<< endl; } ~Value() { cout << "~Value()" << endl; } }; void Vector_user() { vector<Value> vec; //vec.resize(10); vec.reserve(10); cout << vec.capacity()<< endl; cout << vec.size()<< endl; } int main() { Vector_user(); return 0; }
resize():改变容器中可存储元素的个数size和capacity,并调用默认的构造函数
#include <iostream> #include <vector> using namespace std; class Value { public: Value() { cout << "Value()"<< endl; } ~Value() { cout << "~Value()" << endl; } }; void Vector_user() { vector<Value> vec; vec.resize(10); //vec.reserve(10); cout << vec.capacity()<< endl; cout << vec.size()<< endl; } int main() { Vector_user(); return 0; }
(5)push_back和emplace
1.push_back()
#include <iostream> #include <vector> using namespace std; class Object { private: int val; public: Object(int x = 0):val(x) { cout << "Object(int x)"<< endl; } Object(const Object& src): val(src.val) { cout << "Object(const Object& src)" << endl; } Object(Object&& src) : val(src.val) { cout << "Object(Object&& src)" << endl; } Object& operator=(const Object& src) { val = src.val; cout << "=" << endl; return *this; } Object& operator=(Object&& src) { val = src.val; cout << "=&" << endl; return *this; } ~Object() { cout << "~Object()" << endl; } }; void fun() { std::vector<Object> vcobj; vcobj.reserve(5); vcobj.push_back(10); //vcobj.push_back(Object(10)); } int main() { fun(); return 0; }
push_back(10);
push_back(Object(10));
两种方式构造对象的顺序个数都相同!
Object obj(10);
vcobj.push_back(obj);
2. emplace()原位构造
void fun() { std::vector<Object> vcobj; vcobj.reserve(5); vcobj.emplace_back(10); }
void fun() { std::vector<Object> vcobj; vcobj.reserve(5); vcobj.emplace_back(Object(10)); }
void fun() { std::vector<Object> vcobj; vcobj.reserve(5); Object obj(10); vcobj.emplace_back(obj); }
(6)关于原位构造(定位new + 完美转发)
定位new:直接在指定的地址空间内调用构造函数
完美转发:保留传参的右值属性
可变参数:根据传参个数类型,调用不同的构造函数
template<class T, class ...Arg> void Make(T* p, Arg... arg) { new(p) T(std::forward<Arg...>(arg)...); } int main() { //1.开辟空间 Object* p = (Object*)malloc(sizeof(Object)); //2.在p指向的地址空间调用构造Object(10) Make(p, 10); //3.释放空间并调用析构函数 delete p; return 0; }
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注我们的更多内容!
赞 (0)