🌈个人主页:羽晨同学
💫个人格言:“成为自己未来的主人~”
迭代器失效
这篇文章是基于上一篇的Vector的模拟实现的补充知识点,首先我们需要重点关注的便是迭代器失效的问题。
void test_vector3(){std::vector<int> v1;v1.push_back(1);v1.push_back(2);v1.push_back(3);v1.push_back(4);v1.push_back(5);std::vector<int>::iterator it = v1.begin();while (it != v1.end()){if (*it % 2 == 0){v1.erase(it);}else{++it;}}for (auto e : v1){cout << e << " ";}cout << endl;}
我们可以看这个erase功能的实现部分
void erase(iterator pos){assert(pos >= _start);assert(pos < _finish);iterator it = pos + 1;while (it != _finish){*(it - 1) = *it;++it;}--_finish;}
其实我们可以分析出来迭代器失效的原因,其原因在于当删除it指示的元素的时候,it未能被重新赋值,it位置后面的数值赋值到了it位置,内存空间位置被改变,从而造成迭代器失效。
而解决迭代器失效的方法就是重新更新迭代器。
void test_vector3(){std::vector<int> v1;v1.push_back(1);v1.push_back(2);v1.push_back(3);v1.push_back(4);v1.push_back(5);std::vector<int>::iterator it = v1.begin();while (it != v1.end()){if (*it % 2 == 0){it=v1.erase(it);}else{++it;}}for (auto e : v1){cout << e << " ";}cout << endl;}
比如说在这段代码当中,我们对迭代器进行重新更新,从而保证了它的时效性。
构造函数的使用
void test_vector5(){vector<int> v1;v1.push_back(1);v1.push_back(2);v1.push_back(3);v1.push_back(4);v1.push_back(5);vector<int> v2(v1);for (auto e : v2){cout << e << " ";}cout << endl;vector<int> v3;v3.push_back(10);v3.push_back(20);v3.push_back(30);v1 = v3;for (auto e : v1){cout << e << " ";}cout << endl;}
void test_vector6(){vector<int> v1;v1.push_back(1);v1.push_back(2);v1.push_back(3);v1.push_back(4);v1.push_back(5);vector<int> v2(v1.begin() + 1, v1.end());for (auto e : v2){cout << e << " ";}cout << endl;string s("hello");vector<int> v3(s.begin(), s.end());for (auto e : v3){cout << e << " ";}cout << endl;list<int> lt;lt.push_back(100);lt.push_back(100);lt.push_back(100);vector<int> v4(lt.begin(), lt.end());for (auto e : v4){cout << e << " ";}cout << endl;}
所以说,其实Vector的兼容性蛮强大的,任何类型的数据都能放在vector中
void test_vector7(){int i = 0;int j(1);int k = int();int x = int(2);vector<string>v1(10);vector<string> v2(10, "xxx");for (auto e : v1){cout << e << " ";}cout << endl;for (auto e : v2){cout << e << " ";}cout << endl;vector <int> v3(10, 1);for (auto e : v3){cout << e << " ";}cout << endl;vector<int> v4(10, 1);for (auto e : v4){cout << e << " ";}cout << endl;}
构造:
A aa1(1, 1);A aa2 = { 2,2 };A aa9{ 2,2 };const A& aa8 = { 1,1 };A aa3(1);A aa4 = 1;A aa5(1);A aa6 = { 1 };A aa7{ 1 };
隐式类型转换
vector<int> v1({ 1,2,3,4,5,6 });vector<int> v2 = { 10,20,30 };for (auto e : v1){cout << e << " ";}cout << endl;for (auto e : v1){cout << e << " ";}cout << endl;
auto il1 = { 1,2,3,4,5,6 };initializer_list<int> il2 = { 1,2,3,4,5,6 };cout << typeid(il1).name() << endl;cout << sizeof(il2) << endl;for (auto e : il1){cout << e << " ";}cout << endl;
initializer_list是一个代理对象,它就是auto的类型,它的大小就是两个指针的大小(一个指向数量的指针,一个指向存储元素的数组)
void test_vector9(){vector<string> v1;v1.push_back("1111111111111111");v1.push_back("1111111111111111");v1.push_back("1111111111111111");v1.push_back("1111111111111111");v1.push_back("1111111111111111");for (auto e : v1){cout << e << " ";}cout << endl;}