当前位置:网站首页>STL preliminary understanding
STL preliminary understanding
2022-07-21 22:42:00 【It was just a gust of wind】
Concept of container :
Sequential containers : The location of the elements of the container is determined by the time and place of entering the container
Associative containers : Container already has rules , The entry element is determined by the rules in the container .
The concept of iterator :
Can first be understood as a pointer , Basic operations on pointers can be performed on iterators .
But an iterator is actually a class . This class encapsulates a pointer
The concept of algorithm :
Problem solving through limited steps .
Separation design :
Through a small case, we can preliminarily understand the separate design of algorithm containers , Linked by iterators :
#include<iostream>
using namespace std;
// Container algorithm is designed separately , Link through iterators :
int mycount(int* start,int * end,int val) // The algorithm counts the number of elements in the container
{
int num = 0;
while (start != end)
{
if (*start == val)
num++;
start++;
}
return num;
}
int main()
{
int arr[] = { 0,12,4,512,0};
int* Abegin = arr; // Iterator start position
int* Aend = &(arr[sizeof(arr) / sizeof(int)]);
int num = mycount(Abegin, Aend, 0);
cout << num;
}
Containers -string Containers :
string Encapsulates the char*, It's a char* The container of
string Containers do not need to consider memory release and out of bounds
char* and string You can go through string Provided c_str() convert
string It's simpler , What I think I need to know :
substr(int pos = 0,int n = npos)const;// Return from pos At the beginning n A string of characters
Containers -vector Containers :
It can be called dynamic array or variable array , Support random access , Iterators can directly +2,-3 etc.
Iterators except v.begin() and v.end() Besides v.rend( Point to the previous position of the first element ) and v,rbegin( Point to last element )
Try to use at, If there is an error, an exception will be thrown ,[] Will not be
vector Containers are also relatively simple , Need to understand the next use swap Function shrinks space , as well as reserve Reserve space
Containers -deque Containers :
Double ended array , Except for tail insertion push_back Deletion at the end pop_back There is also a head plug push_front And header deletion pop_front
Random storage is also supported
Understand through small cases deque and vector:
#include<iostream>
#include<algorithm>
#include<vector>
#include<deque>
using namespace std;
class Person // Create a player class
{
public:
Person();
Person(int score, string name);
~Person();
public:
int Pscore;
string Pname;
};
Person::Person()
{
Pscore = 0;
Pname = " ";
}
Person::Person(int score, string name):Pname(name),Pscore(score)
{
}
Person::~Person()
{
}
void SetPerson(vector<Person>& v)// Create players
{
string nameseed = "ABCDE";
for(int i = 0;i<5;i++)
{
Person p;
p.Pname = " player ";
p.Pname += nameseed[i];
p.Pscore = 0;
v.push_back(p);
}
}
void SetScore(vector<Person>& v) // Scoring
{
for (vector<Person>::iterator it = v.begin(); it != v.end(); ++it)
{
deque<int>dScore;
for (int i = 0; i < 10; ++i)
{
int score = rand() % 41 + 60;
dScore.push_back(score);
}
dScore.pop_back();
dScore.pop_front();
int sumScore = 0;
int AvgScore = 0;
for (deque<int>::iterator itt = dScore.begin(); itt != dScore.end(); ++itt)
{
sumScore += (*itt);
}
AvgScore = sumScore / dScore.size();
(*it).Pscore = AvgScore;
}
}
bool Paixu(const Person& p1, const Person& p2)
{
return p1.Pscore > p2.Pscore;
}
void Mysort(vector<Person>& v) // Descending order
{
sort(v.begin(), v.end(), Paixu);
for (vector<Person>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << " full name : " << (*it).Pname << " score : " << (*it).Pscore << endl;
}
}
int main()
{
vector<Person>v1;
SetPerson(v1);
SetScore(v1);
Mysort(v1);
}
Containers -stack Containers ( Stack container ):
Iterators are not provided -> Can not traverse , Random access is not supported
You can return the top element
Containers -queue Containers ( Queue container ):
Iterators are not provided -> Can not traverse , Random access is not supported
You can put back the tail or head element
Containers -list:
A linked list consists of a series of nodes , Nodes contain data fields and pointer fields . Memory is non contiguous .
Linked lists allocate memory only when needed , The linked list also needs additional space to save the predecessor successor relationship of nodes
set/multiset Containers :
set The elements of the container are both key values and real values .
Based on the red black tree set Containers do not allow duplicate elements , and multiset allow
Cannot pass set The iterator of changes the value of the element
set Search operation :
lower_bound(keyElem) // Return to the first key>=keyElem Iterators for elements
upper_bound(keyElem) // Return to the first key>keyElem Iterators for elements
equal_range(keyElem) // Return to container key And keyElem Two iterators with equal upper and lower bounds ( The above two return together ) Receive with a pair
map/multimap Containers :
map With key value and real value , All elements are sorted by key value , The bottom is also a red black tree .
map No repetition key, and multimap allow .
map All stored in are pairs
Example :
#include<algorithm>
#include<vector>
#include<map>
#include<time.h>
#include<stdio.h>
using namespace std;
#define SALE_DEPATMENT 1// Sales Department
#define DEVELOP_DEPATMENT 2// R & D department
#define FINACIAL_DEPATMENT 3// The financial department
class Worker {
public:
string Wname;
int Wage;
int Wsalary;
string Wtele;
};
void CreatWorker(vector<Worker>& v) // Create employees
{
string nameseed = "ABCDE";
for (int i = 0; i < 5; i++)
{
Worker w;
w.Wname = " staff ";
w.Wname += nameseed[i];
w.Wtele = "8208798";
w.Wage = rand() % 10 + 30;
w.Wsalary = rand() % 10000 + 10000;
v.push_back(w);
}
}
void WorkerBygroup(vector<Worker>& v, multimap<int, Worker>& m) // Grouping
{
for (vector<Worker>::iterator it = v.begin(); it != v.end(); it++)
{
int depatID = rand() % 3+1;
switch (depatID)
{
case SALE_DEPATMENT:
m.insert(make_pair(SALE_DEPATMENT, *it));
break;
case DEVELOP_DEPATMENT:
m.insert(make_pair(DEVELOP_DEPATMENT, *it));
break;
case FINACIAL_DEPATMENT:
m.insert(make_pair(FINACIAL_DEPATMENT, *it));
break;
default:
break;
}
}
}
void showgropuworker(int depatID, multimap<int, Worker>& m)
{
multimap<int, Worker>::iterator it = m.find(depatID);
int count = m.count(depatID);
int num = 0;
for (multimap<int, Worker>::iterator pos = it; it != m.end() && num < count; pos++, num++)
{
cout << " full name : " << (*pos).second.Wname << " Age : " << (*pos).second.Wage
<< " Telephone " << (*pos).second.Wtele << " Wages : " << (*pos).second.Wsalary << endl;
}
}
void PrintBygropu(multimap<int, Worker>& m)
{
cout << " Sales Department " << endl;
showgropuworker(SALE_DEPATMENT, m);
cout << " R & D department " << endl;
showgropuworker(DEVELOP_DEPATMENT, m);
cout << " The financial department " << endl;
showgropuworker(FINACIAL_DEPATMENT, m);
}
int main()
{
vector<Worker>v1;
multimap<int,Worker>m1;
// Create employees
CreatWorker(v1);
// Employee grouping
WorkerBygroup(v1, m1);
// Print employee information
PrintBygropu(m1);
}
Get to know for the first time STL, It's a long way to go , Here are the notes first
Add :
Question on force deduction :deque、queue、vector Comprehensive problem solving https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/submissions/
It's a test STL Basics
边栏推荐
猜你喜欢
表达式求值
2021普及组总结
Paoding solves the fiboracci sequence and knapsack problem - analyze the optimization process of the two problems in detail, and take you to understand dynamic programming from the most basic problem!
Explain the principle, classification and function of microphone array in detail
What is PCBA? What is the importance of PCBA testing?
第三周ACM训练报告
234. Palindrome linked list
What are the characteristics and application fields of Bluetooth module in the Internet of things?
299. Guessing numbers game
Probability theory - maximum likelihood estimation
随机推荐
Combinatorial summary
第十一周ACM训练报告
数据可视化图表插件开发作品大赏(一)
QT初学者
148. Sorting linked list
437. Path sum III
Using UUID as MySQL primary key, my boss broke up
堆-原理到應用——堆排序、優先級隊列
P2814 家谱(字符串并查集)
438. 找到字符串中所有字母异位词
第六周ACM训练报告
取石子
D - AND and SUM (AtCoder Beginner Contest 238)
What is an electronic scale weighing module? What functions does it have?
XML详解
Programmation créative / groupe primaire (4e - 6e année) - graphisme créatif
Probability theory - variance and covariance, correlation coefficient
How to complete the design of RGB lamp Bluetooth mesh module from 0 to 1
概率论-最大似然估计
2022ACM夏季集训周报(一)