当前位置:网站首页>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/vDdJ9
http://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;
}边栏推荐
- How to rotate the synchronized / refreshed icon (EL icon refresh)
- poj 2762 Going from u to v or from v to u? (infer whether it is a weak link diagram)
- 哪些偏门项目可以做到?自媒体做到月赚一万以上很难吗?
- 98. 验证二叉搜索树 ●●
- Common static methods of math class
- MySQL delete uniqueness constraint unique
- [Yu Yue education] NC machining technology reference materials of Shaanxi University of science and technology
- el-cascader的使用以及报错解决
- Scala concurrent programming (II) akka
- 《牛客刷verilog》Part III Verilog企业真题
猜你喜欢

The PNG image is normal when LabVIEW is opened, and the full black image is obtained when Photoshop is opened

Live tiktok shop 2022 latest gameplay card slot overseas live e-commerce new traffic

STM32__06—单通道ADC

CIS基准测试工具kube-bench使用

rsync远程同步

Rasa 3. X learning series -rasa x Community Edition (Free Edition) changes
![[original] what is the core of programmer team management?](/img/11/d4b9929e8aadcaee019f656cb3b9fb.png)
[original] what is the core of programmer team management?

Neural structured learning - Part 2: training with natural graphs

Switching power supply buck circuit CCM and DCM working mode

多普勒效应(多普勒频移)
随机推荐
Brushless drive design -- on MOS drive circuit
MySQL replace primary key delete primary key add primary key
11gR2 Database Services for &quot;Policy&quot; and &quot;Administrator&quot; Managed Databases (文件 I
Zero rhino technology joined hands with the intelligence Club: the "causal faction" forum was successfully held, and the "causal revolution" brought the next generation of trusted AI
Rasa 3.x 学习系列-Rasa X 社区版(免费版) 更改
C file and folder operation
【EF Core】EF Core与C# 数据类型映射关系
VS2010编写动态链接库DLL和单元测试,转让DLL测试的正确性
Convert Chinese into pinyin
TVS管和ESD管的技术指标和选型指南-嘉立创推荐
4 points tell you the advantages of the combination of real-time chat and chat robots
orgchart. JS organization chart, presenting structural data in an elegant way
How to improve eloquence
There are 14 God note taking methods. Just choose one move to improve your learning and work efficiency by 100 times!
poj 2762 Going from u to v or from v to u? (推断它是否是一个薄弱环节图)
Breadth first search open turntable lock
(4) UART application design and simulation verification 2 - RX module design (stateless machine)
MySQL (2) -- simple query, conditional query
Design and implementation of secsha system
Spire. PDF for NET 8.7.2