# Vector简单实现

2 篇文章 0 订阅
#include <iostream>
#include <initializer_list>
#include <algorithm>
#include <stdexcept>
#include <string>

template <typename T>
class Vector {
public:
Vector(int size);
Vector(std::initializer_list<T> lst);
Vector(const Vector<T>& vec);
Vector<T>& operator=(const Vector<T>& vec);
Vector(Vector<T>&& vec);
Vector<T>& operator=(Vector<T>&& vec);
~Vector() {delete[] elem;}

T* begin() {return elem;}
const T* begin() const {return elem;}
T* end() { return elem+sz;}
const T* end() const { return elem+sz;}
T& operator[](int i);
int size() const;
private:
T* elem;
int sz;
};

template <typename T>
Vector<T>::Vector(int size)
{
if (size < 0) throw std::out_of_range{"Vector"};
elem = new T[size];
sz = size;
}

template <typename T>
Vector<T>::Vector(std::initializer_list<T> lst):elem{new T[lst.size()]}, sz{lst.size()}
{
std::copy(lst.begin(), lst.end(), begin());
}

template <typename T>
Vector<T>::Vector(const Vector<T>& vec):elem{new T[vec.size()]}, sz{vec.size()}
{
std::copy(vec.begin(), vec.end(), begin());
}

template <typename T>
Vector<T>& Vector<T>::operator=(const Vector<T>& vec)
{
delete[] elem;
auto p = new T[vec.size()];
std::copy(p, p+vec.size(), vec.begin());
elem = p;
sz = vec.size();
return *this;
}

template <typename T>
Vector<T>::Vector(Vector<T>&& vec):elem{vec.elem}, sz{vec.sz}
{
vec.elem = nullptr;
vec.sz = 0;
}

template <typename T>
Vector<T>& Vector<T>::operator=(Vector<T>&& vec)
{
delete[] elem;
elem = vec.elem;
sz = vec.sz;
vec.elem = nullptr;
vec.sz = 0;
return *this;
}

template <typename T>
T& Vector<T>::operator[](int i)
{
if (i<0 || i>=sz) throw std::out_of_range{"operator[]"};
return elem[i];
}

template <typename T>
int Vector<T>::size() const
{
return sz;
}

int main()
{
Vector<int> ivec{1,2,3,4,5};
Vector<std::string> svec{"zhangdaochao", "haozhiwei"};
//for(auto i : ivec)
//	std::cout << i << std::endl;
//for(auto s : svec)
//	std::cout << s << std::endl;
Vector<int> ivec2{ivec};
std::cout << "ivec1:\t";
for(auto i : ivec)
std::cout << i << " ";
std::cout << std::endl;
std::cout << "ivec2:\t";
for(auto i2 : ivec2)
std::cout << i2 << " ";
std::cout << std::endl;
std::cout << "svec:\t";
Vector<std::string> svec2 = std::move(svec);
for(auto s : svec)
std::cout << s << " ";
std::cout << std::endl;
std::cout << "svec2:\t";
for(auto s2 : svec2)
std::cout << s2 << " ";
}


• 0
点赞
• 3
收藏
觉得还不错? 一键收藏
• 0
评论
07-21
08-14 596
07-25 940
09-22 746
03-07 946
12-01
08-05
03-27
03-24 234
05-25 1529
09-18 695
03-17 248

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。