赞
踩
目录
使用STL的三个境界:能用、明理、能扩展。
构造函数声明 | 接口说明 |
vector() | 无参构造 |
vector(size_type n, const value_type& val = value_type()) | 构造并初始化n个val |
vector(const vector& x) | 拷贝构造 |
vector(Inputlterator first, Inputlterator last) | 使用迭代器进行初始化构造 |
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- int TestVector1()
- {
- vector<int> first;
- vector<int> second(4, 100);
- vector<int> third(second.begin(), second.end());
- vector<int> fourth(third);
-
- int myints[] = { 16,2,77,29 };
- vector<int> fifth(myints, myints + sizeof(myints) / sizeof(int));
-
- cout << "The contents of fifth are:";
-
- for (vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
- cout << ' ' << *it;
-
- cout << endl;
-
- return 0;
- }
-
- int main()
- {
-
- TestVector1();
-
- return 0;
- }

iterator的使用 | 接口说明 |
begin + end | 获取第一个数据位置的iterator / const_iterator,获取最后一个数据的下一个位置的iterator / const_iterator |
rbegin + rend | 获取最后一个数据位置的reverse_iterator,获取第一个数据前一个位置的reverse_iteratorreverse_iterator |
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- void PrintVector(const vector<int>& v)
- {
- // const对象使用const迭代器进行遍历打印
- vector<int>::const_iterator it = v.begin();
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
- }
-
- void TestVector2()
- {
- vector<int> v;
-
- v.push_back(1);
- v.push_back(2);
- v.push_back(3);
- v.push_back(4);
-
- // 使用迭代器进行遍历打印
- vector<int>::iterator it = v.begin();
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- // 使用迭代器进行修改
- it = v.begin();
- while (it != v.end())
- {
- *it *= 2;
- ++it;
- }
-
- // 使用反向迭代器进行遍历再打印
- // vector<int>::reverse_iterator rit = v.rbegin();
- auto rit = v.rbegin();
- while (rit != v.rend())
- {
- cout << *rit << " ";
- ++rit;
- }
- cout << endl;
-
- PrintVector(v);
- }
-
- int main()
- {
-
- TestVector2();
-
- return 0;
- }

容量空间 | 接口说明 |
size | 获取数据个数 |
capacity | 获取容量大小 |
empty | 判断是否为空 |
resize | 改变vector的size |
reverse | 改变vector的capacity |
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- // 将有效元素个数设置为n个,如果时增多时,增多的元素使用data进行填充
- // 注意:resize在增多元素个数时可能会扩容
- void TestVector3()
- {
- vector<int> v;
-
- for (int i = 1; i < 10; i++)
- v.push_back(i);
-
- v.resize(5);
- v.resize(8, 100);
- v.resize(12);
-
- cout << "v contains:";
- for (size_t i = 0; i < v.size(); i++)
- cout << ' ' << v[i];
- cout << endl;
- }
-
- // 测试vector的默认扩容机制
- // vs:按照1.5倍方式扩容
- // linux:按照2倍方式扩容
- void TestVectorExpand()
- {
- size_t sz;
- vector<int> v;
-
- sz = v.capacity();
-
- cout << "making v grow:" << endl;
- for (int i = 0; i < 100; ++i)
- {
- v.push_back(i);
- if (sz != v.capacity())
- {
- sz = v.capacity();
- cout << "capacity changed: " << sz << endl;
- }
- }
- }
-
- // 往vecotr中插入元素时,如果大概已经知道要存放多少个元素
- // 可以通过reserve方法提前将容量设置好,避免边插入边扩容效率低
- void TestVectorExpandOP()
- {
- vector<int> v;
- size_t sz = v.capacity();
-
- // 提前将容量设置好,可以避免一遍插入一遍扩容
- v.reserve(100);
-
- cout << "making bar grow:" << endl;
- for (int i = 0; i < 100; ++i)
- {
- v.push_back(i);
- if (sz != v.capacity())
- {
- sz = v.capacity();
- cout << "capacity changed: " << sz << endl;
- }
- }
- }
-
- int main()
- {
-
- TestVector3();
- TestVectorExpand();
- TestVectorExpandOP();
-
- return 0;
- }

vector增删查改 | 接口说明 |
push_back | 尾插 |
pop_back | 尾删 |
find | 查找 |
insert | 在position之前插入val |
erase | 删除position位置的数据 |
swap | 交换两个vector的数据空间 |
operator[] | 像数组一样访问 |
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- void TestVector4()
- {
- vector<int> v;
-
- v.push_back(1);
- v.push_back(2);
- v.push_back(3);
- v.push_back(4);
-
- auto it = v.begin();
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- v.pop_back();
- v.pop_back();
-
- it = v.begin();
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
- }
-
- // 任意位置插入:insert和erase,以及查找find
- // 注意find不是vector自身提供的方法,是STL提供的算法
- void TestVector5()
- {
- // 使用列表方式初始化,C++11新语法
- vector<int> v{ 1, 2, 3, 4 };
-
- // 在指定位置前插入值为val的元素,比如:3之前插入30,如果没有则不插入
- // 1. 先使用find查找3所在位置
- // 注意:vector没有提供find方法,如果要查找只能使用STL提供的全局find
- auto pos = find(v.begin(), v.end(), 3);
- if (pos != v.end())
- {
- // 2. 在pos位置之前插入30
- v.insert(pos, 30);
- }
-
- vector<int>::iterator it = v.begin();
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- pos = find(v.begin(), v.end(), 3);
- // 删除pos位置的数据
- v.erase(pos);
-
- it = v.begin();
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
- }
-
- // operator[]+index 和 C++11中vector的新式for+auto的遍历
- // vector使用这两种遍历方式是比较便捷的。
- void TestVector6()
- {
- vector<int> v{ 1, 2, 3, 4 };
-
- // 通过[]读写第0个位置。
- v[0] = 10;
- cout << v[0] << endl;
-
- // 1. 使用for+[]小标方式遍历
- for (size_t i = 0; i < v.size(); ++i)
- cout << v[i] << " ";
- cout << endl;
-
- vector<int> swapv;
- swapv.swap(v);
-
- cout << "v data:";
- for (size_t i = 0; i < v.size(); ++i)
- cout << v[i] << " ";
- cout << endl;
-
- // 2. 使用迭代器遍历
- cout << "swapv data:";
-
- auto it = swapv.begin();
- while (it != swapv.end())
- {
- cout << *it << " ";
- ++it;
- }
-
- // 3. 使用范围for遍历
- for (auto x : v)
- cout << x << " ";
- cout << endl;
- }
-
- int main()
- {
-
- TestVector4();
- TestVector5();
- TestVector6();
-
- return 0;
- }

迭代器的主要作用就是让算法能够不用关心底层数据结构,其底层实际就是一个指针,或者是对指针进行了封装,比如:vector的迭代器就是原生态指针T*。因此迭代器失效,实际就是迭代器底层对应指针所指向的空间被销毁了,而使用一块已经被释放的空间,造成的后果是程序崩溃(即如果继续使用已经失效的迭代器,程序可能会崩溃)。
对于vector可能会导致其迭代器失效的操作有:
1. 会引起其底层空间改变的操作,都有可能是迭代器失效,比如:resize、reverse、insert、assign、push_back等。
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- int main()
- {
- vector<int> v{ 1,2,3,4,5,6 };
-
- auto it = v.begin();
-
- // 将有效元素个数增加到100个,多出的位置使用8填充,操作期间底层会扩容
- // v.resize(100, 8);
-
- // reserve的作用就是改变扩容大小但不改变有效元素个数,操作期间可能会引起底层容量改变
- // v.reserve(100);
-
- // 插入元素期间,可能会引起扩容,而导致原空间被释放
- // v.insert(v.begin(), 0);
- // v.push_back(8);
-
- // 给vector重新赋值,可能会引起底层容量改变
- v.assign(100, 8);
-
- /*
- 出错原因:以上操作,都有可能会导致vector扩容,也就是说vector底层原理旧空间被释放掉,
- 而在打印时,it还使用的是释放之间的旧空间,在对it迭代器操作时,实际操作的是一块已经被释放的
- 空间,而引起代码运行时崩溃。
- 解决方式:在以上操作完成之后,如果想要继续通过迭代器操作vector中的元素,只需给it重新
- 赋值即可。
- */
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- return 0;
- }

2. 指定位置元素的删除 -> erase
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- int main()
- {
- int a[] = { 1, 2, 3, 4 };
-
- vector<int> v(a, a + sizeof(a) / sizeof(int));
-
- // 使用find查找3所在位置的iterator
- vector<int>::iterator pos = find(v.begin(), v.end(), 3);
-
- // 删除pos位置的数据,导致pos迭代器失效。
- v.erase(pos);
-
- cout << *pos << endl; // 此处会导致非法访问
-
- return 0;
- }

erase删除pos位置元素后,pos位置之后的元素会往前搬移,没有导致底层空间的改变,理论上迭代器不会失效,但是:如果pos刚好是最后一个元素,删完之后pos刚好是end的位置,而end位置是没有元素的,那么pos就失效了。因此删除vector中任意位置上元素时,vs就认为该位置迭代器失效了。
3. 注意:Linux下,g++编译器对迭代器失效的检测不是非常严格,处理也没有vs下极端。
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- // 1. 扩容之后,迭代器已经失效了,程序虽然可以运行,但是运行结果已经不对了
- int main()
- {
- vector<int> v{ 1,2,3,4,5 };
-
- for (size_t i = 0; i < v.size(); ++i)
- cout << v[i] << " ";
- cout << endl;
-
- auto it = v.begin();
- cout << "扩容之前,vector的容量为: " << v.capacity() << endl;
-
- // 通过reserve将底层空间设置为100,目的是为了让vector的迭代器失效
- v.reserve(100);
- cout << "扩容之后,vector的容量为: " << v.capacity() << endl;
-
- // 经过上述reserve之后,it迭代器肯定会失效,在vs下程序就直接崩溃了,但是linux下不会
- // 虽然可能运行,但是输出的结果是不对的
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- return 0;
- }

- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- // 2. erase删除任意位置代码后,linux下迭代器并没有失效
- // 因为空间还是原来的空间,后序元素往前搬移了,it的位置还是有效的
- int main()
- {
- vector<int> v{ 1,2,3,4,5 };
-
- vector<int>::iterator it = find(v.begin(), v.end(), 3);
- v.erase(it);
-
- cout << *it << endl;
- while (it != v.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- return 0;
- }

- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <vector>
- using namespace std;
-
- // 3: erase删除的迭代器如果是最后一个元素,删除之后it已经超过end
- // 此时迭代器是无效的,++it导致程序崩溃
- int main()
- {
- vector<int> v{ 1,2,3,4,5 };
-
- auto it = v.begin();
- while (it != v.end())
- {
- if (*it % 2 == 0)
- v.erase(it);
- ++it;
- }
-
- for (auto e : v)
- cout << e << " ";
- cout << endl;
-
- return 0;
- }

从上述三个例子可以看到:SGI STL中,迭代器失效后,代码并不一定会崩溃,但是运行结果肯定不对,如果it不在begin和end范围内,肯定会崩溃。
4. 与vector类似,string在插入+扩容操作+erase后,迭代器也会失效
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- using namespace std;
-
- void TestString()
- {
- string s("hello");
- auto it = s.begin();
-
- // 放开之后代码会崩溃,因为resize到20会string会进行扩容
- // 扩容之后,it指向之前旧空间已经被释放了,该迭代器就失效了
- // 后序打印时,再访问it指向的空间程序就会崩溃
- //s.resize(20, '!');
- while (it != s.end())
- {
- cout << *it;
- ++it;
- }
-
- cout << endl;
-
- it = s.begin();
- while (it != s.end())
- {
- it = s.erase(it);
- // 按照下面方式写,运行时程序会崩溃,因为erase(it)之后
- // it位置的迭代器就失效了
- // s.erase(it);
- ++it;
- }
- }
-
- int main()
- {
-
- TestString();
-
- return 0;
- }

迭代器失效的解决方法:在使用前,对迭代器重新赋值即可。
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <assert.h>
- using namespace std;
-
- namespace fyd
- {
- template<class T>
- class vector
- {
- public:
- // Vector的迭代器是一个原生指针
- typedef T* iterator;
- typedef const T* const_iterator;
-
- ///
- // 构造和销毁
- vector()
- : _start(nullptr)
- , _finish(nullptr)
- , _endOfStorage(nullptr)
- {}
-
- vector(size_t n, const T& value = T())
- : _start(nullptr)
- , _finish(nullptr)
- , _endOfStorage(nullptr)
- {
- reserve(n);
- while (n--)
- {
- push_back(value);
- }
- }
-
- /*
- * 理论上将,提供了vector(size_t n, const T& value = T())之后
- * vector(int n, const T& value = T())就不需要提供了,但是对于:
- * vector<int> v(10, 5);
- * 编译器在编译时,认为T已经被实例化为int,而10和5编译器会默认其为int类型
- * 就不会走vector(size_t n, const T& value = T())这个构造方法,
- * 最终选择的是:vector(InputIterator first, InputIterator last)
- * 因为编译器觉得区间构造两个参数类型一致,因此编译器就会将InputIterator实例化为int
- * 但是10和5根本不是一个区间,编译时就报错了
- * 故需要增加该构造方法
- */
- vector(int n, const T& value = T())
- : _start(new T[n])
- , _finish(_start + n)
- , _endOfStorage(_finish)
- {
- for (int i = 0; i < n; ++i)
- {
- _start[i] = value;
- }
- }
-
- // 若使用iterator做迭代器,会导致初始化的迭代器区间[first,last)只能是vector的迭代器
- // 重新声明迭代器,迭代器区间[first,last)可以是任意容器的迭代器
- template<class InputIterator>
- vector(InputIterator first, InputIterator last)
- {
- while (first != last)
- {
- push_back(*first);
- ++first;
- }
- }
-
- vector(const vector<T>& v)
- : _start(nullptr)
- , _finish(nullptr)
- , _endOfStorage(nullptr)
- {
- reserve(v.capacity());
- iterator it = begin();
- const_iterator vit = v.cbegin();
- while (vit != v.cend())
- {
- *it++ = *vit++;
- }
-
- _finish = it;
- }
-
- vector<T>& operator=(vector<T> v)
- {
- swap(v);
-
- return *this;
- }
-
- ~vector()
- {
- if (_start)
- {
- delete[] _start;
-
- _start = _finish = _endOfStorage = nullptr;
- }
- }
-
- /
- // 迭代器相关
- iterator begin()
- {
- return _start;
- }
-
- iterator end()
- {
- return _finish;
- }
-
- const_iterator cbegin() const
- {
- return _start;
- }
-
- const_iterator cend() const
- {
- return _finish;
- }
-
- //
- // 容量相关
- size_t size() const
- {
- return _finish - _start;
- }
-
- size_t capacity() const
- {
- return _endOfStorage - _start;
- }
-
- bool empty() const
- {
- return _start == _finish;
- }
-
- void reserve(size_t n)
- {
- if (n > capacity())
- {
- size_t oldSize = size();
-
- // 1. 开辟新空间
- T* tmp = new T[n];
-
- if (_start)
- {
- for (size_t i = 0; i < oldSize; ++i)
- tmp[i] = _start[i];
-
- // 3. 释放旧空间
- delete[] _start;
- }
-
- _start = tmp;
- _finish = _start + oldSize;
- _endOfStorage = _start + n;
- }
- }
-
- void resize(size_t n, const T& value = T())
- {
- // 1.如果n小于当前的size,则数据个数缩小到n
- if (n <= size())
- {
- _finish = _start + n;
-
- return;
- }
-
- // 2.空间不够则增容
- if (n > capacity())
- reserve(n);
-
- // 3.将size扩大到n
- iterator it = _finish;
-
- _finish = _start + n;
- while (it != _finish)
- {
- *it = value;
- ++it;
- }
- }
-
- ///
- // 元素访问
- T& operator[](size_t pos)
- {
- assert(pos < size());
-
- return _start[pos];
- }
-
- const T& operator[](size_t pos)const
- {
- assert(pos < size());
-
- return _start[pos];
- }
-
- T& front()
- {
- return *_start;
- }
-
- const T& front()const
- {
- return *_start;
- }
-
- T& back()
- {
- return *(_finish - 1);
- }
-
- const T& back()const
- {
- return *(_finish - 1);
- }
-
- /
- // vector的修改操作
- void push_back(const T& x)
- {
- insert(end(), x);
- }
-
- void pop_back()
- {
- erase(end() - 1);
- }
-
- void swap(vector<T>& v)
- {
- std::swap(_start, v._start);
- std::swap(_finish, v._finish);
- std::swap(_endOfStorage, v._endOfStorage);
- }
-
- iterator insert(iterator pos, const T& x)
- {
- assert(pos <= _finish);
-
- // 空间不够先进行增容
- if (_finish == _endOfStorage)
- {
- //size_t size = size();
- size_t newCapacity = (0 == capacity()) ? 1 : capacity() * 2;
- reserve(newCapacity);
-
- // 如果发生了增容,需要重置pos
- pos = _start + size();
- }
-
- iterator end = _finish - 1;
- while (end >= pos)
- {
- *(end + 1) = *end;
- --end;
- }
-
- *pos = x;
- ++_finish;
-
- return pos;
- }
-
- // 返回删除数据的下一个数据
- // 方便解决:一边遍历一边删除的迭代器失效问题
- iterator erase(iterator pos)
- {
- // 挪动数据进行删除
- iterator begin = pos + 1;
- while (begin != _finish)
- {
- *(begin - 1) = *begin;
- ++begin;
- }
-
- --_finish;
-
- return pos;
- }
-
- private:
- iterator _start; // 指向数据块的开始
- iterator _finish; // 指向有效数据的尾
- iterator _endOfStorage; // 指向存储容量的尾
- };
- }
-
- /// /
- /// 测试
- void TestVector1()
- {
- fyd::vector<int> v1;
- fyd::vector<int> v2(10, 5);
-
- int array[] = { 1,2,3,4,5 };
- fyd::vector<int> v3(array, array + sizeof(array) / sizeof(array[0]));
-
- fyd::vector<int> v4(v3);
-
- for (size_t i = 0; i < v2.size(); ++i)
- {
- cout << v2[i] << " ";
- }
- cout << endl;
-
- auto it = v3.begin();
- while (it != v3.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- for (auto e : v4)
- {
- cout << e << " ";
- }
- cout << endl;
- }
-
- void TestVector2()
- {
- fyd::vector<int> v;
-
- v.push_back(1);
- v.push_back(2);
- v.push_back(3);
- v.push_back(4);
- v.push_back(5);
-
- cout << v.size() << endl;
- cout << v.capacity() << endl;
- cout << v.front() << endl;
- cout << v.back() << endl;
- cout << v[0] << endl;
- for (auto e : v)
- {
- cout << e << " ";
- }
- cout << endl;
-
- v.pop_back();
- v.pop_back();
- for (auto e : v)
- {
- cout << e << " ";
- }
- cout << endl;
-
- v.insert(v.begin(), 0);
- for (auto e : v)
- {
- cout << e << " ";
- }
- cout << endl;
-
- v.erase(v.begin() + 1);
- for (auto e : v)
- {
- cout << e << " ";
- }
- cout << endl;
- }
-
- int main()
- {
-
- TestVector1();
- TestVector2();
-
- return 0;
- }

在vector模拟实现的reverse接口中,若使用memcpy进行拷贝,以下代码会发生什么问题?
- int main()
- {
- fyd::vector<std::string> v;
-
- v.push_back("1111");
- v.push_back("2222");
- v.push_back("3333");
-
- return 0;
- }
分析:
结论:如果对象中涉及到资源管理时,千万不能使用memcpy进行对象之间的拷贝,因为memcpy是浅拷贝,否则可能会引起内存泄漏甚至程序崩溃。
- // 以杨辉三角的前n行为例:假设n为5
- void TestVector3(size_t n)
- {
- // 使用vector定义二维数组vv,vv中的每个元素都是vector<int>
- fyd::vector<fyd::vector<int>> vv(n);
- // 将二维数组每一行中的vecotr<int>中的元素全部设置为1
- for (size_t i = 0; i < n; ++i)
- vv[i].resize(i + 1, 1);
-
- // 给杨辉三角出第一列和对角线的所有元素赋值
- for (int i = 2; i < n; ++i)
- {
- for (int j = 1; j < i; ++j)
- {
- vv[i][j] = vv[i - 1][j] + vv[i - 1][j - 1];
- }
- }
- }

fyd::vector<fyd::vector<int>> vv(n);构造一个vv动态二维数组,vv中总共有n个元素,每个元素都是vector类型的,每行没有包含任何元素。
填充完成后:
使用标准库中vector构建动态二维数组时与上图一致。
感谢大佬们的支持!!!
互三啦!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。