STL—Vector详解

1.vector的介绍和使用

vector实际上是一个类模板,allocator (对象分配的元素的类型) 是第二个模板参数。

2.vector的使用

(1) vector的定义

cpp 复制代码
int TestVector1()
{
    // constructors used in the same order as described above:
    vector<int> first;                                // empty vector of ints
    vector<int> second(4, 100);                       // four ints with value 100
    vector<int> third(second.begin(), second.end());  // iterating through second
    vector<int> fourth(third);                       // a copy of 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;//The contents of fifth are: 16 2 77 29
    cout << '\n';
    
    return 0;
}

(2) vector iterator的使用

迭代器的使用:

cpp 复制代码
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()
{
	// 使用push_back插入4个数据
	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);
}

(3) vector 的空间增长问题

cpp 复制代码
// 测试vector的默认扩容机制
void TestVectorExpand()
{
    size_t sz;
    vector<int> v;
    sz = v.capacity();
    cout << "making v grow:\n";
    for (int i = 0; i < 100; ++i)
    {
        v.push_back(i);
        if (sz != v.capacity())
        {
            sz = v.capacity();
            cout << "capacity changed: " << sz << '\n';
        }
    }
}

● capacity的代码在vs和g++下分别运行会发现,vs下capacity是按1.5倍增长的,g++是按2
倍增长的。这个问题经常会考察,不要固化的认为,vector增容都是2倍,具体增长多少是
根据具体的需求定义的。vs是PJ版本STL,g++是SGI版本STL

cpp 复制代码
// 如果已经确定vector中要存储元素大概个数,可以提前将空间设置足够
// 就可以避免边插入边扩容导致效率低下的问题了
void TestVectorExpandOP()
{
    vector<int> v;
    size_t sz = v.capacity();
    v.reserve(100); // 提前将容量设置好,可以避免一遍插入一遍扩容
    cout << "making bar grow:\n";
    for (int i = 0; i < 100; ++i)
    {
        v.push_back(i);
        if (sz != v.capacity())
        {
            sz = v.capacity();
            cout << "capacity changed: " << sz << '\n';
        }
    }
}

vector与string的reserve接口不同的是:vector在n小于当前向量容量的情况下,函数调用不会导致重新分配,向量容量也不会受到影响(强制性);而string再该情况下,被视为缩小字符串容量的非绑定请求:容器实现可以自由地进行优化,使字符串的容量大于n。 (不具有约束力的请求)
● reserve只负责开辟空间,如果确定知道需要用多少空间,reserve可以缓解vector增容的代价缺陷问题 。

cpp 复制代码
// reisze(size_t n, const T& data = T())
// 将有效元素个数设置为n个,如果时增多时,增多的元素使用data进行填充
// 注意:resize在增多元素个数时可能会扩容
void TestVector3()
{
	vector<int> v;

	// set some initial content:
	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 << '\n';
}

● resize在开空间的同时还会进行初始化,影响size。

(4) vector 的增删查改

注: operator[ ]与at() 区别:

  • operator[] 方法在访问元素时不会检查索引是否越界。
  • 如果索引超出了容器的边界,它不会抛出异常,而是返回一个指向容器内部某个位置的引用。
  • at() 方法在访问元素时会检查索引是否越界。
  • 如果索引超出了容器的边界,它会抛出一个std::out_of_range异常。
cpp 复制代码
void TestVector1()
{
	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 TestVector2()
{
	// 使用列表方式初始化,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;
}

void test3()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    print_vactor(v);

    //删除所有的偶数
    auto it = v.begin();
    while (it != v.end())
    {
        if (*it % 2 == 0)
        {
            it = v.erase(it);//erese会返回删除数据的下一个位置,相当于已经++it了
        }
        else
        {
            ++it;
        }
    }
    print_vactor(v);
}

// operator[]+index 和 C++11中vector的新式for+auto的遍历
// vector使用这两种遍历方式是比较便捷的。
void TestVector4()
{
	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;
}

(5) vector迭代器失效问题

迭代器的主要作用就是让算法能够不用关心底层数据结构,其底层实际就是一个指针,或者是对指针进行了封装,比如:vector的迭代器就是原生态指针T* 。因此迭代器失效,实际就是迭代器底层对应指针所指向的空间被销毁了,而使用一块已经被释放的空间,造成的后果是程序崩溃(即如果继续使用已经失效的迭代器,程序可能会崩溃)。
对于vector可能会导致其迭代器失效的操作有:

1.野指针

(1) 会引起其底层空间改变的操作,都有可能是迭代器失效 ,比如:resize、reserve、insert、 assign、push_back等。 vs下系统会强制检查,访问就会报错
解决方式:在以上操作完成之后,如果想要继续通过迭代器操作vector中的元素,只需给 it重新赋值即可

cpp 复制代码
#include <iostream>
using namespace std;
#include <vector>
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

指定位置元素的删除操作--erase

cpp 复制代码
#include <iostream>
using namespace std;
#include <vector>
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.失去原有意义

(1)没有发生扩容,但迭代器指向位置已经没有意义,由于数据挪动,迭代器已经不是指向原来的数字而是指向修改后的数,所以insert以后我们认为迭代器也失效了 。

cpp 复制代码
template<class T>
void print_vactor(const vector<T>& v)
{
    auto it = v.begin();
    while (it != v.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;

    for (auto e : v)
    {
        cout << e << " ";
    }
    cout << endl;
}
void test()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    print_vactor(v);

    int x;
    cin >> x;
    auto p = find(v.begin(), v.end(), x);
    if (p != v.end())
    {
        p = v.insert(p, 20);
        //此时p已经不是指向原来的2了,我们认为是迭代器失效
        (*p) *= 10;
    }
    print_vactor(v);

}
int main()
{
    test();
    return 0;
}

4. Linux下

注意:Linux下,g++编译器对迭代器失效的检测并不是非常严格,处理也没有vs下极端
(1) 扩容之后,迭代器已经失效了,程序虽然可以运行,但是运行结果已经不对了

cpp 复制代码
// 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;
}

程序输出:
1 2 3 4 5
扩容之前,vector的容量为: 5
扩容之后,vector的容量为: 100
0 2 3 4 5 409 1 2 3 4 5
(2)erase删除任意位置代码后,linux下迭代器并没有失效,因为空间还是原来的空间,后序元素往前搬移了,it的位置还是有效的

cpp 复制代码
// 2. erase删除任意位置代码后,linux下迭代器并没有失效
// 因为空间还是原来的空间,后序元素往前搬移了,it的位置还是有效的
#include <vector>
#include <algorithm>
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;
}

程序可以正常运行,并打印:
4
4 5
(3)erase删除的迭代器如果是最后一个元素,删除之后it已经超过end ,此时迭代器是无效的,++it导致程序崩溃

cpp 复制代码
// 3: erase删除的迭代器如果是最后一个元素,删除之后it已经超过end
// 此时迭代器是无效的,++it导致程序崩溃
int main()
{
    vector<int> v{1,2,3,4,5};
    // vector<int> v{1,2,3,4,5,6};
    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;
}

=========================================================
// 使用第一组数据时,程序可以运行
[sly@VM-0-3-centos 20220114]$ g++ testVector.cpp -std=c++11
[sly@VM-0-3-centos 20220114]$ ./a.out
1 3 5
=========================================================
// 使用第二组数据时,程序最终会崩溃
[sly@VM-0-3-centos 20220114]$ vim testVector.cpp
[sly@VM-0-3-centos 20220114]$ g++ testVector.cpp -std=c++11
[sly@VM-0-3-centos 20220114]$ ./a.out
Segmentation fault
从上述三个例子中可以看到:SGI STL中,迭代器失效后,代码并不一定会崩溃,但是运行
结果肯定不对,如果it不在begin和end范围内,肯定会崩溃的。


5.其他容器(string)

与vector类似,string在插入+扩容操作+erase之后,迭代器也会失效。

几乎所有的容器erase后都会发生迭代器失效,insert看情况。

cpp 复制代码
#include <string>
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;
	}
}

6.总结

迭代器失效解决办法:在使用前,对迭代器重新赋值即可(返回值接收)

3.动态二维数组

简图:

(1) 代码理解:

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;
int main() 
{
	//动态二维数组
	vector<int> v(5, 1);//用5个1创建一维数组
	vector<vector<int>> vv(10, v);//10个一维数组创建10行5列的二维数组
	vv[1][2] = 2;//修改数据,调用两种operator[]

	//打印二维数组
	for (size_t i = 0; i < vv.size(); i++)
	{
		for (size_t j = 0; j < vv[i].size(); j++) 
		{
			cout << vv[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
	
	return 0;
}

(2) 杨辉三角

cpp 复制代码
// 以杨慧三角的前n行为例:假设n为5
void test2vector(size_t n)
{
	// 使用vector定义二维数组vv,vv中的每个元素都是vector<int>
	vector<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];
			}
	}
}

构造一个vv动态二维数组,vv中总共有n个元素,每个元素 都是vector类型的,每行没有包含任何元素,如果n为5时如下所示:

4.vector的模拟实现

(1) 注意事项1-6

1 .规定:类模板在没有实例化时,迭代器无法读取!编译器不能区分这里const_iterator是类型还是静态成员变量。要想解决:第一可以在前面加上typename用来证明这里是类型;第二是用auto,系统判断为类型。

cpp 复制代码
//打印模版
template<class T>
void print_vector(const vector<T>& v)
{
    // 规定,没有实例化的类模板里面取东西,编译器不能区分这里const_iterator
    // 是类型还是静态成员变量
    //typename vector<T>::const_iterator it = v.begin();
    auto it = v.begin();
    while (it != v.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;

    for (auto e : v)
    {
        cout << e << " ";
    }
    cout << endl;
}

2. 内置类型是没有构造函数的概念的,但为了兼容模板(T val = T( ) ),也产生默认构造函数用来构造

cpp 复制代码
 // 内置类型是没有构造函数的概念的,
// 但为了兼容模板(T val = T() ),也会产生默认构造函数来构造
vector(int n, const T& value = T())
{
    reserve(n);
    while (n--)
    {
        push_back(value);
    }
}

3. c++11中有强制生成默认构造,即使类中已有其他构造函数,也能强制生成。eg:vector( ) = default。

cpp 复制代码
 //c++11规定,default可以强制生成默认构造
 vector() = default;

4. 类里面可以用类名替代类型(特殊化),类外面规定:类名不能代表类型

cpp 复制代码
//类里面可以用类名替代类型(特殊化)
//vector & operator=(vector v)
vector<T>& operator= (vector<T> v)
{
    swap(v);
    return *this;
}

5. 类模板的成员函数,还可继续是函数模板。

为了让该类模板的成员函数不光是应用于某一类容器的成员函数,而是使任意容器迭代器初始化,但前提是类型要匹配(与模板实现时所用的数据类型匹配)。(下面代码在vector类里面实现)此时不光可以用来构造vector也可以构造list等容器。

// 若使用iterator做迭代器,会导致初始化的迭代器区间[first,last)只能是vector的迭代器
// 重新声明迭代器,迭代器区间[first,last)可以是任意容器的迭代器

cpp 复制代码
//类模板的成员函数可以继续是函数模板
template<class InputIterator>;
vector(InputIterator first, InputIterator last)
{
    while (first != last)
    {
        push_back(*first);
        ++first;
    }
}

实现:

cpp 复制代码
//用vector来初始化string
vector(size_t n, const T& val = T())
{
    reserve(n);
    for (int i = 0; i < n; i++)
    {
        push_back(val);
    }
}

6. vector(int n, const T& value = T())

* 理论上,提供了vector(size_tn, const T& value = T())之后
* vector(intn, 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根本不是一个区间,编译时就报错了
* 故需要增加该构造方法

cpp 复制代码
vector(size_t n, const T& value = T())
{
    reserve(n);
    while (n--)
    {
        push_back(value);
    }
} 
vector(int n, const T& value = T())
{
    reserve(n);
    while (n--)
    {
        push_back(value);
    }
}

(2) 模拟实现及测试

cpp 复制代码
#include<iostream>
#include<assert.h>
#include<vector>
using namespace std;

namespace zyt
{
	template <class T>
	class vector
	{
    public:

        // Vector的迭代器是一个原生指针

        typedef T* iterator;

        typedef const T* const_iterator;

        iterator begin()
        {
            return _start;
        }

        iterator end()
        {
            return _finish;
        }

        const_iterator cbegin() const
        {
            return _start;
        }

        const_iterator cend() const
        {
            return _finish;
        }

        // construct and destroy
        //初始化列表
        vector()
        {}
        //c++11规定,default可以强制生成默认构造即使类中已有其他构造函数,也能强制生成
        vector() = default;
       
        // 内置类型是没有构造函数的概念的,
        // 但为了兼容模板(T val = T() ),也会产生默认构造函数来构造
        vector(size_t n, const T& value = T())
        {
            reserve(n);
            while (n--)
            {
                push_back(value);
            }
        }
          
        vector(int n, const T& value = T())
        {
            reserve(n);
            while (n--)
            {
                push_back(value);
            }
        }
        
///
        //构造一个包含与范围[first,last)一样多的元素的容器
        //每个元素都按照相同的顺序从该范围内的相应元素构造而成

        // 若使用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)
        {
            reserve(v.capacity());

            iterator it = begin();
            const_iterator vit = v.cbegin();
            while (vit != v.cend())
            {
                *it = *vit;
                ++it;
                ++vit;
            }
            _finish = it;
        }
        //类里面可以用类名替代类型(特殊化),类外面规定:类名不能代表类型
        //vector & operator=(vector v)
        vector<T>& operator= (vector<T> v)
        {
            swap(v);
            return *this;
        }

        ~vector()
        {
            delete[] _start;
            _start = _finish = _end_of_storage = nullptr;
        }

        // capacity

        size_t size() const
        {
            return _finish - _start;
        }

        size_t capacity() const
        {
            return _end_of_storage - _start;
        }

        void reserve(size_t n)
        {
            if (n > capacity())
            {
                size_t oldsize = _finish - _start;//防止更新空间后size()失效

                T* tmp = new T[n];
                if (_start)
                {
                    //这里不能用memcpy
                    //memcpy(tmp, _start, old_size * sizeof(T));
                    for (size_t i = 0; i < size(); i++)
                    {
                        tmp[i] = _start[i];//拷贝数据
                    }

                    delete[] _start;//释放旧空间
                }
                _start = tmp;
                _finish = _start + oldsize;
                _end_of_storage = _start + n;
            }
        }

        void resize(size_t n, const T& value = T())
        {
            if (n <= size())
            {
                _finish = _start + n;
                return;
            }

            if (n > capacity())
                reserve(n);

            // n > size,从原来的结束位置到n位置要用val填补
            iterator pos = _finish;
            _finish = _start + n;
            while (pos < _finish)
            {
                (*pos) = value;
                ++pos;
            }
        }

        ///access///

        T& operator[](size_t pos)
        {
            return _start[pos];
        }

        const T& operator[](size_t pos)const
        {
            return _start[pos];
        }
        
        ///modify/

        void push_back(const T& x)
        {
            if (size() == capacity())
            {
                reserve(capacity() == 0 ? 4 : capacity() * 2);
            }
            *_finish = x;
            ++_finish;
        }

        void pop_back()
        {
            --_finish;
        }

        void swap(vector<T>& v)
        {
            std::swap(_start, v._start);
            std::swap(_finish, v._finish);
            std::swap(_end_of_storage, v._end_of_storage);
        }

        iterator insert(iterator pos, const T& x)
        {
            assert(pos <= _finish);
            if (_finish == _end_of_storage)
            {
                size_t len = pos - _start;
                reserve(capacity() == 0 ? 4 : capacity() * 2);

                pos = _start + len;//reserve后开新空间,要更新pos
            }

            iterator end = _finish;
            while (pos < end)
            {
                *(end) = *(end - 1);
                --end;
            }
            *pos = x;
            ++_finish;
            return pos;
        }
        // 返回删除数据的下一个数据
        // 方便解决:一边遍历一边删除的迭代器失效问题
        iterator erase(iterator pos)
        {
            assert(pos <= _finish);
            iterator cur = pos + 1;
            while (cur != _finish)
            {
                *(cur - 1) = *cur;
                ++cur;
            }
            --_finish;
            return pos;
        }

	private:
		iterator _start = nullptr;          // 指向数据块的开始
		iterator _finish = nullptr;         // 指向有效数据的尾
		iterator _end_of_storage = nullptr; // 指向存储容量的尾
	};

    void test1();
    void test2();

    template<class T>
    void print_vector(const vector<T>& v)
    {
        // 规定,没有实例化的类模板里面取东西,编译器不能区分这里const_iterator
        // 是类型还是静态成员变量
        //typename vector<T>::const_iterator it = v.begin();
        auto it = v.begin();
        while (it != v.end())
        {
            cout << *it << " ";
            ++it;
        }
        cout << endl;

        for (auto e : v)
        {
            cout << e << " ";
        }
        cout << endl;
    }
    //打印各类容器
    template<class Container>
    void print_container(const Container& v)
    {
        auto it = v.cbegin();
        while (it != v.cend())
        {
            cout << *it << " ";
            ++it;
        }
        cout << endl;

        //for (auto e : v)
        //{
        //    cout << e << " ";
        //}
        //cout << endl;
    }
}

void zyt::test1()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    zyt::print_container(v);

    //v.pop_back();
    //v.pop_back();
    //v.pop_back();
    //v.pop_back();
    //print_vector(v);
    
    v.insert(v.begin() + 1, 20);
    v.insert(v.begin() + 4, 20);
    v.insert(v.end(), 8);
    zyt::print_container(v);

    v.erase(v.begin());
    v.erase(v.begin() + 3);
    v.erase(v.end()-1);
    zyt::print_container(v);

    cout << v[1] << endl;
    v.resize(4, 0);
    zyt::print_container(v);

    v.resize(6, 0);
    zyt::print_container(v);

    v.resize(5, 0);
    zyt::print_container(v);

}

void zyt::test2()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    zyt::print_container(v);

    vector<int> vv = v;
    zyt::print_container(v);

    
    v.push_back(4);
    v.push_back(5);
    vv = v;
    zyt::print_container(v);

}

int main()
{
    zyt::test2();
    return 0;
}

(3) 使用memcpy拷贝问题

假设模拟实现的vector中的reserve接口中,使用memcpy进行的拷贝,以下代码会发生什么问题?

cpp 复制代码
int main()
{
    zyt::vector<std::string> v;
    v.push_back("1111");
    v.push_back("2222");
    v.push_back("3333");
    zyt::print_container(v);
    return 0;
}

问题分析:
1. memcpy是内存的二进制格式拷贝,将一段内存空间中内容原封不动的拷贝到另外一段内存空间中
2. 如果拷贝的是自定义类型的元素,memcpy既高效又不会出错,但如果拷贝的是自定义类型元素,并且自定义类型元素中涉及到资源管理时,就会出错,因为memcpy的拷贝实际是浅拷贝。

结论:如果对象中涉及到资源管理时,千万不能使用memcpy进行对象之间的拷贝,因为
memcpy是浅拷贝,否则可能会引起内存泄漏甚至程序崩溃。

相关推荐
limingade1 小时前
手机实时提取SIM卡打电话的信令和声音-新的篇章(一、可行的方案探讨)
物联网·算法·智能手机·数据分析·信息与通信
编程零零七1 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286112 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py2 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy2 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
jiao000014 小时前
数据结构——队列
c语言·数据结构·算法
C-SDN花园GGbond4 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处5 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ5 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
leon6255 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab