当前位置:网站首页>Initialiser votre vecteur & initialisateur avec une liste Introduction à la Liste
Initialiser votre vecteur & initialisateur avec une liste Introduction à la Liste
2022-07-05 23:44:00 【Demi - lune】
Table des matières
2. Avecinitializer_listPour construire une listevector
L'initialisation avec une liste est"{}"Pour initialiser votrevectorConteneur pour une implémentation personnalisée égale.Nous pouvons voirSTLDonnées dans la bibliothèquevector,list,mapAttendez, les conteneurs sont prêts."{}"Pour initialiser,Par exemple:
vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
list<int> l={ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
map<int, int> m = { { 1, 1 }, { 2, 2 }, { 3, 3 } };
Alors comment est - ce possible?En fait, la façon dont il est mis en œuvre n'est pas aussi grande que dans votre phénomène.,Il en a utilisé un.initializer_listPour recevoir"{}"L'élément dans leinitializer_list Pour le constructeur de la liste des paramètres puis implémenter via "{}" Pour construire des conteneurs .
1. initializer_list
Je vais vous présenterinitializer_list:
On peut voir qu'il est C++11Oui., Alors ça veut dire avant C++98 La construction d'objets avec des listes n'est pas prise en charge . Il n'y a que trois façons.
Faisons un test.
2. Avecinitializer_listPour construire une listevector
Ici, je vaisvector Le code complet de l'implémentation analogique est donné pour protéger certains lecteurs de vector Les détails de la mise en oeuvre ne sont pas clairs et ne comprennent pas comment les mettre en oeuvre avec la liste vectorLa construction de: Je vais encore utiliser initializer_list Les codes partiels sont présentés séparément pour illustrer .(Si c'est vrai.vector Le Code de l'implémentation analogique est douteux en ce qui me concerne vector Analyse détaillée du blog implémenté par simulation :http://t.csdn.cn/vDdJ9http://t.csdn.cn/vDdJ9)
#include<iostream>
#include<assert.h>
#include<vector>
#include<initializer_list>
using namespace std;
namespace wbx
{
template<class T>
class vector
{
public:
typedef T* iterator;
typedef const T* const_iterator;
/Tectonique et tectonique
vector()
:_start(nullptr)
, _finish(nullptr)
, end_of_storage(nullptr)
{}
// Construire avec une liste vector:
vector(initializer_list<T> l)
{
_start = new T[l.size()];
_finish = _start;
auto it = l.begin();
while (it != l.end())
{
*_finish = *it;
_finish++;
it++;
}
end_of_storage = _finish;
}
// Assigner une valeur à une liste vector:
vector<T>& operator=(initializer_list<T> l)
{
reserve(l.size());
_finish = _start;
auto it = l.begin();
while (it != l.end())
{
*_finish = *it;
_finish++;
it++;
}
return *this;
}
vector(size_t n, const T &val = T())//Structuren- Oui.TTypevalValeur
:_start(nullptr)// Pointeur pour initialiser c'est une bonne habitude de programmation
,_finish(nullptr)
,end_of_storage(nullptr)
{
_start = new T[n*sizeof(T)];
_finish = _start+n;
end_of_storage = _finish;
for (size_t i = 0; i < n; i++)
{
_start[i] = val;
}
}
vector(int n,const T &val = T())//Structuren- Oui.TTypevalValeur,Ici.valIl faut utiliserconst Modifier sinon la compilation ne passera pas lorsque les paramètres entrants
:_start(nullptr)// Pointeur pour initialiser c'est une bonne habitude de programmation
, _finish(nullptr)
, end_of_storage(nullptr)
{
_start = new T[n*sizeof(T)];
_finish = _start + n;
end_of_storage = _finish;
for (int i = 0; i < n; i++)
{
_start[i] = val;
}
}
vector(const vector<T> &v)//Copier la construction
:_start(nullptr),
_finish(nullptr),
end_of_storage(nullptr)
{
//vector temp(v.begin(), v.end());// Il n'est pas possible d'appeler ici un pointeur d'Itérateur de retour de type normal ,
vector<T> temp(v.cbegin(), v.cend());//Parce queconstL'objet ne peut invoquer queconstFonction membre de type
this->swap(temp);
}
template<class Iterator>// Voici un autre modèle pour une classe d'Itérateur , Parce que supposons ici que nous vector Différents types d'objets stockés dans
// Le type d'Itérateur retourné est également différent , Donc nous réinitialisons ici une classe de modèle pour une variété de
// Les types sont d'application générale
vector(Iterator first, Iterator last)
{
size_t n = last - first; //Obtenir icifristEtlast La distance entre les deux doit être écrite distanceFonction
// Prenez la distance entre eux , Ceci est écrit ici parce qu'une simple mise en œuvre analogique
_start = new T[n];
_finish = _start;
end_of_storage = _start + n;
while (first != last)
{
*_finish = *first;
_finish++;
first++;
}
}
~vector()
{
if (_start)
{
delete[] _start;
_start = nullptr;
_finish = nullptr;
end_of_storage = nullptr;
}
}
Surcharge de l'opérateur:
vector <T>operator=(vector<T> v)
{
this->swap(v);
return *this;
}
T& operator[](size_t index)
{
if (index < 0 || index >= size())
{
assert(false);
}
return *(_start + index) ;
}
///Capacité relative
size_t size()
{
int a = 0;
return a=_finish - _start;
}
size_t capacity()
{
return end_of_storage - _start;
}
bool empty()
{
if (_start == _finish)
{
return true;
}
return false;
}
void resize(size_t n, T val = T())
{
size_t oldsize = size();
if (n >capacity())
{
reserve(n - capacity());
}
for (int i = oldsize; i < n; i++)
{
_start[i] = val;
}
_finish = _start + n;//Si le nouveausize Moins vieux size Pas d'accès direct ici
}
void reserve(size_t n)
{
if (n>capacity())
{
T *temp = new T[n];
for (int i = 0; i < size(); i++)
{
temp[i] = _start[i];//Il faut utiliser= Pour faire une copie si vous utilisez autre chose comme memcpy Il y aura des copies peu profondes
}
size_t oldsize = size();
if (_start)
{
delete[] _start;
}
_start = temp;
_finish = _start + oldsize;
end_of_storage = _start + n;
}
}
Itérateur
iterator begin()
{
return _start;
}
iterator end()
{
return _finish;
}
const_iterator cbegin()const
{
return _start;
}
const_iterator cend()const
{
return _finish;
}
/Insérer une fonction
void push_back(T val)
{
if (_finish == end_of_storage)
{
reserve(2 * capacity());
}
*_finish = val;
_finish++;
}
void pop_back()
{
if (empty())
{
assert(false);
}
_finish--;
}
iterator insert(iterator pos,T val)
{
if (empty()||pos==_finish)
{
push_back(val);
return pos;
}
if (_finish == end_of_storage)
{
reserve(capacity() + 1);
}
iterator temp = _finish-1;
while (temp >= pos)
{
*(temp + 1) = *temp;
temp--;
}
*pos = val;
_finish++;
return pos;
}
iterator erase(iterator pos)
{
if (pos < _start || pos >= _finish)
{
assert(false);
}
iterator ret = pos;
while (pos != _finish - 1)
{
*pos = *(pos + 1);
pos++;
}
_finish--;
return ret + 1;
}
T & front()
{
return *(_start);
}
T &back()
{
return *(_finish-1);
}
Fonction d'échange
void swap(vector <T> &v)
{
std::swap(v._start, _start);
std:: swap(v._finish, _finish);
std::swap(v.end_of_storage, end_of_storage);
}
private:
iterator _start;
iterator _finish;
iterator end_of_storage;
};
}
using namespace std;
wbx::vector<int> static v4(5, 4);
void test1()
{
wbx::vector<int> v1{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
cout << "v1: ";
for (int i = 0; i < v1.size(); i++)
{
cout << v1[i] << " ";
}
cout << endl;
wbx::vector<int> v2;
v2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
cout << "v2: ";
for (int i = 0; i < v2.size(); i++)
{
cout << v2[i] << " ";
}
cout << endl;
wbx::vector<int> v3(11);
v3 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
cout << "v3: ";
for (int i = 0; i < v3.size(); i++)
{
cout << v3[i] << " ";
}
cout << endl;
cout << v1.size() << endl;
cout << v2.size() << endl;
cout << v3.size() << endl;
cout << v1.capacity() << endl;
cout << v2.capacity() << endl;
cout << v3.capacity() << endl;
}
À propos deinitializer_listCode partiel: Vous pouvez voir que la mise en œuvre est très simple ,Ça marche.initializer_list Une paire d'éléments à l'intérieur vector Attribution de la boucle spatiale .
// Construire avec une liste vector:
vector(initializer_list<T> l)
{
_start = new T[l.size()];//Ici.start- Oui.vector Adresse de départ du pointeur pour l'espace de tableau de gestion sous - jacent
_finish = _start;
auto it = l.begin();
while (it != l.end())
{
*_finish = *it;//finish- Oui.vector Position finale du tableau sous - jacent
_finish++;
it++;
}
end_of_storage = _finish;//end_of_storage- Oui.vector La position finale de l'espace ouvert
}
// Assigner une valeur à une liste vector:
vector<T>& operator=(initializer_list<T> l)
{
reserve(l.size());
_finish = _start;
auto it = l.begin();
while (it != l.end())
{
*_finish = *it;
_finish++;
it++;
}
return *this;
}
边栏推荐
- Rasa 3.x 学习系列-Rasa 3.2.1 新版本发布
- MySQL delete uniqueness constraint unique
- When to use useImperativeHandle, useLayoutEffect, and useDebugValue
- rsync远程同步
- GFS distributed file system
- C# 反射与Type
- PV静态创建和动态创建
- [SQL] SQL expansion languages of mainstream databases (T-SQL, pl/sql, pl/pgsql)
- MySQL (1) -- related concepts, SQL classification, and simple operations
- Part III Verilog enterprise real topic of "Niuke brush Verilog"
猜你喜欢
随机推荐
698. Divided into k equal subsets ●●
14 MySQL-视图
2022.6.20-6.26 AI industry weekly (issue 103): new little life
VS2010编写动态链接库DLL和单元测试,转让DLL测试的正确性
[original] what is the core of programmer team management?
GFS分布式文件系统
Tips for using pads router
保研笔记二 软件工程与计算卷二(13-16章)
[Yu Yue education] NC machining technology reference materials of Shaanxi University of science and technology
How to design API return code (error code)?
Design and implementation of secsha system
Opencvsharp (C openCV) shape detection and recognition (with source code)
How to rotate the synchronized / refreshed icon (EL icon refresh)
保研笔记四 软件工程与计算卷二(8-12章)
Biased sample variance, unbiased sample variance
证明 poj 1014 模优化修剪,部分递归 有错误
Spreadjs 15.1 CN and spreadjs 15.1 en
MySQL delete uniqueness constraint unique
15 MySQL stored procedures and functions
Cwaitabletimer timer, used to create timer object access