当前位置:网站首页>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;
}
边栏推荐
- VS2010编写动态链接库DLL和单元测试,转让DLL测试的正确性
- 保研笔记四 软件工程与计算卷二(8-12章)
- 芯源&立创EDA训练营——无刷电机驱动
- 4 points tell you the advantages of the combination of real-time chat and chat robots
- 保研笔记一 软件工程与计算卷二(1-7章)
- It is proved that POJ 1014 module is optimized and pruned, and some recursion is wrong
- [original] what is the core of programmer team management?
- Neural structured learning - Part 3: training with synthesized graphs
- MySQL (2) -- simple query, conditional query
- 【经典控制理论】自控实验总结
猜你喜欢
随机推荐
Spire Office 7.5.4 for NET
做自媒体影视短视频剪辑号,在哪儿下载素材?
20220703 周赛:知道秘密的人数-动规(题解)
Biased sample variance, unbiased sample variance
How to insert data into MySQL database- How can I insert data into a MySQL database?
如何让同步/刷新的图标(el-icon-refresh)旋转起来
MySQL (2) -- simple query, conditional query
15 MySQL-存储过程与函数
Idea connects to MySQL, and it is convenient to paste the URL of the configuration file directly
Rethinking about MySQL query optimization
How to rotate the synchronized / refreshed icon (EL icon refresh)
【LeetCode】5. Valid palindrome
VS2010编写动态链接库DLL和单元测试,转让DLL测试的正确性
STM32__06—单通道ADC
带外和带内的区别
Scala concurrent programming (II) akka
grafana工具界面显示报错influxDB Error
TVS管和ESD管的技術指標和選型指南-嘉立創推薦
Spire. PDF for NET 8.7.2
In C#, why can't I modify the member of a value type instance in a foreach loop?