当前位置:网站首页>【STL】vector
【STL】vector
2022-07-07 19:54:00 【Yuucho】
List of articles
1. vector
vector It means vector in Chinese , It is a dynamic order table that can change size .
2. vector Common interfaces
2.1 Constructors
constructor | Interface specification |
---|---|
vector()( a key ) | No arguments structure |
vector (const vector& x); ( a key ) | Copy structure |
vector(size_type n, const value_type& val = value_type()) | Construct and initialize n individual val |
vector (InputIterator first, InputIterator last); | Use iterators for initialization construction |
vector Is a class template , It can not only store int、double Other types , It can also store string, Strictly speaking vector Can store any type .
void test_vector1()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
vector<double> v2;
v2.push_back(1.1);
v2.push_back(2.2);
v2.push_back(3.3);
vector<string> v3;
// One parameter constructors support implicit conversions
//string(const char* str)
//string s = "hello world";
// A constant string constructs a temporary object
// Then copy the structure to s
// Optimized into direct construction s
v3.push_back(" Li Bai ");
v3.push_back(" Du Fu ");
v3.push_back(" Su shi ");
v3.push_back(" Bai Juyi ");
//10 individual 5 initialization
vector<int> v4(10, 5);
// Iterator interval initialization
vector<string> v5(++v3.begin(), --v3.end());
string s = "hello world";
vector<char> v6(s.begin(), s.end());
}
test :
2.2 Traverse
void test_vector2()
{
// Traverse
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
// 1、 Subscript +[]
for (size_t i = 0; i < v.size(); ++i)
{
v[i] += 1;
cout << v[i] << " ";
}
cout << endl;
// 2. iterator
vector<int>::iterator it = v.begin();
while (it != v.end())
{
*it -= 1;
cout << *it << " ";
++it;
}
cout << endl;
// 3. Range for
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
}
test :
2.3 increase capacity
void test_vector3()
{
size_t sz;
vector<int> foo;
// Current capacity
sz = foo.capacity();
// increase capacity , If the capacity changes, print it
cout << "making foo grow:\n";
for (int i = 0; i < 100; ++i)
{
foo.push_back(i);
if (sz != foo.capacity())
{
sz = foo.capacity();
cout << "capacity changed: " << sz << '\n';
}
}
}
vs2019 Next test :vs(PJ edition STL) It's probably 1.5 Double capacity increase .
Linux Next :g++(SGI edition STL) Is in accordance with the 2 Multiplied by .
g++ Running results :
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 4
capacity changed: 8
capacity changed: 16
capacity changed: 32
capacity changed: 64
capacity changed: 128
Analysis of how much words can be added :
The more capacity is increased in a single time , Insert N It's worth , The less capacity increase times , The more efficient .
The more capacity is increased in a single time , Maybe the more waste .
The single increase is less , It will lead to frequent capacity increase , inefficiency ,
therefore VS、Linux Choose... Separately 1.5 Times and 2 Double capacity , This is also the result of balancing .
If we already know how much space to use , You can use it reserve Open the space well in advance (resize Will change size, The insertion will still expand ):
2.4 shrink_to_fit
string、vector All have one characteristic : Delete data , Generally, they will not actively shrink the volume .vector Provide shrink_to_fit To request the container to reduce its capacity to accommodate its size .
shrink_to_fit The shortcomings of :
(1) If you want to insert data later , It will be expanded again , Then why shrink the volume !
(2) The operating system does not allow part of the memory , Therefore, the actual operation of volume reduction is to apply for a volume reduction size first ( Assuming that n Bytes ) Space , Then put the front of the original space n Copy bytes , Then release the original space .
shrink_to_fit At the cost of performance , I suggest you use it with caution .
void test_vector4()
{
size_t sz;
vector<int> foo;
foo.reserve(100);
foo.resize(10);
cout << foo.size() << endl;
cout << foo.capacity() << endl;
// Use with caution 、 To use less
foo.shrink_to_fit();
cout << foo.size() << endl;
cout << foo.capacity() << endl;
}
test :
2.5 insert and erase
vector Of insert Subscripts are not supported , Only iterators are supported .
void test_vector5()
{
// Traverse
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.insert(v.begin(), -1);
v.insert(v.begin(), -2);
v.insert(v.begin(), -3);
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
v.insert(v.begin()+7, 300);
//v.insert(v.begin()+8, 300); Transboundary , Illegal iterator location
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
v.erase(v.begin());
v.erase(v.begin());
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
}
2.6 find
vector No lookup function , But it can be reused algorithm In the database find.
void test_vector6()
{
// Traverse
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
//vector<int>::iterator pos = find(v.begin(), v.end(), 3);
auto pos = find(v.begin(), v.end(), 3);
if (pos != v.end())
{
cout << " eureka " << endl;
v.erase(pos);
}
else
{
cout << " Can't find " << endl;
}
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
}
2.7 sort
void test_vector7()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(0);
v.push_back(9);
v.push_back(3);
v.push_back(1);
// The default is ascending
sort(v.begin(), v.end());
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
// In descending order , functor
// About affine functions , Remember this usage first , Let's talk about the queue later, and then talk about it in detail
sort(v.begin(), v.end(), greater<int>()); // >
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
}
3. Exercises
3.1 Yang hui triangle
Yang hui triangle
About the topic vector(vector<int>)
:
The core idea : Find out the law of Yang Hui triangle , I found that the beginning and end of each line are 1, In the middle [j] The number is equal to the previous line [j-1]+
[j]
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> vv;
// First open up the space of Yang Hui triangle
vv.resize(numRows);
// Initialize each row
for(size_t i = 0; i < numRows; ++i)
{
// The number of each line increases in turn
vv[i].resize(i+1, 0);
// The first and last of each line are 1
vv[i][0] = 1;
vv[i][vv[i].size()-1] = 1;
}
for(size_t i = 0; i < vv.size(); ++i)
{
for(size_t j = 0; j < vv[i].size(); ++j)
{
if(vv[i][j] == 0)
{
// The position between is equal to the previous line j-1 and j Add up
vv[i][j] = vv[i-1][j-1] + vv[i-1][j];
}
}
}
return vv;
}
};
C Language reference code :
边栏推荐
- 杰理之按键发起配对【篇】
- 杰理之相同声道的耳机不允许配对【篇】
- 648. 单词替换
- Kirin Xin'an with heterogeneous integration cloud financial information and innovation solutions appeared at the 15th Hunan Financial Technology Exchange Conference
- R language ggplot2 visualization: use the ggecdf function of ggpubr package to visualize the grouping experience cumulative density distribution function curve, and the linetype parameter to specify t
- 关于ssh登录时卡顿30s左右的问题调试处理
- R语言ggplot2可视化:使用ggpubr包的ggecdf函数可视化分组经验累积密度分布函数曲线、linetype参数指定不同分组曲线的线型
- UCloud是基础云计算服务提供商
- Visual Studio 插件之CodeMaid自动整理代码
- tp6 实现佣金排行榜
猜你喜欢
杰理之手动配对方式【篇】
Install mysql8 for Linux X ultra detailed graphic tutorial
PV static creation and dynamic creation
干货分享|DevExpress v22.1原版帮助文档下载集合
PMP对工作有益吗?怎么选择靠谱平台让备考更省心省力!!!
Jürgen Schmidhuber回顾LSTM论文等发表25周年:Long Short-Term Memory. All computable metaverses. Hierarchical reinforcement learning (RL). Meta-RL. Abstractions in generative adversarial RL. Soccer learn
9 原子操作类之18罗汉增强
Jerry's headphones with the same channel are not allowed to pair [article]
Netease Yunxin participated in the preparation of the standard "real time audio and video service (RTC) basic capability requirements and evaluation methods" issued by the Chinese Academy of Communica
Matplotlib drawing 3D graphics
随机推荐
Classification automatique des cellules de modules photovoltaïques par défaut dans les images de lecture électronique - notes de lecture de thèse
Kunpeng developer summit 2022 | Kirin Xin'an and Kunpeng jointly build a new ecosystem of computing industry
2022.07.02
杰理之关于 TWS 声道配置【篇】
Automatic classification of defective photovoltaic module cells in electroluminescence images-論文閱讀筆記
【剑指offer】剑指 Offer II 012. 左右两边子数组的和相等
[Verilog advanced challenge of Niuke network question brushing series] ~ multi bit MUX synchronizer
How to open an account for stock speculation? Excuse me, is it safe to open a stock account by mobile phone?
Ucloud is a basic cloud computing service provider
Key points of anti reptile: identifying reptiles
最多可以参加的会议数目[贪心 + 优先队列]
# 欢迎使用Markdown编辑器
模拟实现string类
【RT-Thread env 工具安装】
杰理之关于 TWS 交叉配对的配置【篇】
LeetCode力扣(剑指offer 36-39)36. 二叉搜索树与双向链表37. 序列化二叉树38. 字符串的排列39. 数组中出现次数超过一半的数字
The DBSCAN function of FPC package of R language performs density clustering analysis on data, checks the clustering labels of all samples, and the table function calculates the two-dimensional contin
R语言fpc包的dbscan函数对数据进行密度聚类分析、查看所有样本的聚类标签、table函数计算聚类簇标签与实际标签构成的二维列联表
时间工具类
Download from MySQL official website: mysql8 for Linux X Version (Graphic explanation)