当前位置:网站首页>STL notes (VI): container vector
STL notes (VI): container vector
2022-07-25 05:09:00 【Reyn Morales】
STL note ( 6、 ... and ): Containers ——vector
In this part , It mainly shows how to use containers , On the one hand, it is how to use the functions provided by each type of container in the standard template library , How to operate containers through these functions ; The other is how to use containers to solve some practical problems
Because the content of this part is too simple , Therefore, only the function of the corresponding container is given how to call , And examples of using these functions , And give a simple summary of some places prone to mistakes
In this part , Another important thing is to understand object-oriented programming ideas and methods , Compare it with the process oriented approach , Experience the difference between the two , Distinguish their strengths and weaknesses , Under what circumstances, what methods are applicable
vector Containers
function
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// General purpose container - vector( The dynamic array , Single port container )
// working principle :
// 1. Expand capacity
// 2. Copy the data
// 3. Additive element
template <typename T>
class MyArray
{
private:
T * pData;
int length;
int total;
public:
MyArray(int n) {
pData = new T[n];
length = 0;
total = n;
}
void Add(T value) {
if (length < total) {
pData[length++] = value;
} else {
total = total * 2; // Double the length
T * temp = new T[total]; // Create array
for (int i = 0; i < length; i++) { // Copy the data
temp[i] = pData[i];
}
temp[length++] = value; // Additive element
delete []pData; // Release space
pData = temp; // Copy the first address of the space
}
}
void Show() {
for (int i = 0; i < length; i++) {
cout << pData[i] << ' ';
}
}
~MyArray() {
if (pData) {
delete []pData;
pData = NULL;
}
}
};
// Definition 、 Initialization and traversal
void Display(vector<int> v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << ' ';
}
cout << endl;
}
void rDisplay(vector<int> v)
{
for (vector<int>::reverse_iterator it = v.rbegin(); it != v.rend(); it++) {
cout << *it << ' ';
}
cout << endl;
}
void test1()
{
vector<int> v1;
vector<int> v2(2); // Number of spaces - 2, Element number - 2, The element value is 0
vector<int> v3(3, 1); // Number of spaces - 3, Element number - 3, Element value 1
int a[3] = {10, 20, 30};
vector<int> v4(a, a + sizeof(a)/sizeof(int));
vector<int> v5(v4.begin(), v4.end()); // Iterator construction
vector<int> v6(v5); // Copy structure
Display(v6);
rDisplay(v6);
vector<int> v7 = v6;
v2.swap(v6); // In exchange for
}
// Access data
void test2()
{
// In the data
vector<int> v;
v.push_back(10);
v.push_back(20);
// Reading data
cout << v[0] << endl; // 10
cout << v.at(0) << endl; // 10 - Detect out of bounds
cout << v.front() << endl; // 10
cout << v.back() << endl; // 20
cout << *(v.begin() + 1) << endl; // 20
}
// Container size
void test3()
{
// max_size
vector<int> v1;
cout << v1.max_size() << endl; // When the container capacity is 0 when , The maximum capacity that the system can provide
// size - capacity
vector<int> v2(2);
cout << v2.size() << endl; // 2
cout << v2.capacity() << endl; // 2
v2.push_back(8);
cout << v2.size() << endl; // 3
cout << v2.capacity() << endl; // 4
Display(v2); // 0 0 8
// resize
v2.resize(10);
cout << v2.size() << endl; // 10
cout << v2.capacity() << endl; // 10
Display(v2); // 0 0 8 0 0 0 0 0 0 0
// reserve - Retain
v2.reserve(10);
cout << v2.size() << endl; // 3
cout <<v2.capacity() << endl; // 10
Display(v2); // 0 0 8
}
// modify
void test4()
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v[0] = 30;
*(v.begin() + 1) = 40;
// Return type - quote
cout << ++v[0] << endl; // 31
cout << ++v.at(0) << endl; // 32
cout << ++v.front() << endl; // 33
cout << ++v.back() << endl; // 41
cout << ++(*v.begin()) << endl; // 34
}
int main()
{
// MyArray<int> arr(2);
// arr.Add(1);
// arr.Add(2);
// arr.Add(3);
// arr.Add(4);
// arr.Add(5);
// arr.Show();
// test1(); // Definition 、 Initialization and traversal
// test2(); // Access data
// test3(); // Container size
// test4(); // Modifying elements
return 0;
}
Case study
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void Display(vector<int> v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << ' ';
}
cout << endl;
}
// Insert and delete
void test5()
{
vector<int> v;
// Insert
v.push_back(10);
v.push_back(20);
v.insert(v.begin(), 5);
v.insert(v.end(), 25); // 5 10 20 25
v.insert(v.begin() + 2, 15); // 5 10 15 20 25
Display(v);
v.insert(v.begin(), 3, 0);
Display(v);
vector<int> temp(2); // 0 0
temp.insert(temp.begin(), v.begin(), v.end());
Display(temp);
// Delete
v.pop_back(); // Delete the last element
Display(v); // 0 0 0 5 10 15 20
v.erase(v.begin() + 3);
Display(v); // 0 0 0 10 15 20
v.erase(v.begin() + 3, v.begin() +5);
Display(v); // 0 0 0 20
v.clear();
}
// Vector Case study : Student management system
class Student {
private:
string Sno; // Student number
string Sname; // full name
int Sage; // Age
public:
Student(string no, string name, int age):Sno(no),Sname(name),Sage(age) {}
string getSno()
{
return Sno;
}
void setSage(int infoModified)
{
Sage = infoModified;
}
void Show()
{
cout << Sno << '\t' << Sname << '\t' << Sage << endl;
}
};
class StudentManagement {
private:
vector<Student> students;
public:
void insertStudent(Student s)
{
students.push_back(s);
}
vector<Student>::iterator serachStudentBySno(string key)
{
for (vector<Student>::iterator it = students.begin(); it != students.end(); it++) {
if (it->getSno() == key) {
return it;
}
}
return students.end();
}
void removeStudentBySno(string key)
{
if (serachStudentBySno(key) != students.end()) {
students.erase(serachStudentBySno(key));
}
}
void modifyStudentSageBySno(string key, int infoModified)
{
if (serachStudentBySno(key) != students.end()) {
serachStudentBySno(key)->setSage(infoModified);
}
}
void displayStudents()
{
for (vector<Student>::iterator it = students.begin(); it != students.end(); it++) {
it->Show();
}
}
void displayStudent(vector<Student>::iterator pos)
{
pos->Show();
}
};
int main()
{
// test5();
Student stu1("1001", "Reyn", 21);
Student stu2("1002", "Lisa", 20);
Student stu3("1003", "Lena", 22);
StudentManagement studentsMS; // Students Manage System
studentsMS.insertStudent(stu1);
studentsMS.insertStudent(stu2);
studentsMS.insertStudent(stu3);
cout << endl << " To display all student information " << endl;
studentsMS.displayStudents();
cout << endl << " Query student information by student number " << endl;
studentsMS.displayStudent(studentsMS.serachStudentBySno("1002"));
cout << endl << " Remove student information with student ID " << endl;
studentsMS.removeStudentBySno("1003");
studentsMS.displayStudents();
cout << endl << " Modify student information with student number " << endl;
studentsMS.displayStudent(studentsMS.serachStudentBySno("1002"));
studentsMS.modifyStudentSageBySno("1002", 21);
studentsMS.displayStudent(studentsMS.serachStudentBySno("1002"));
return 0;
}
summary
- vector In essence, it is a dynamic array , That is, when the container capacity is not enough to hold the next element , Expand the capacity of the container to accommodate more elements
- vector One possible way to implement the principle of dynamic arrays is , First expand the capacity of the container , Then copy the original data to a container with larger capacity , Then add the element to be added
- vector In the constructor of , If a certain space is initialized in advance , Then the number of elements is equal to the length of space , And its element values are all zero
- vector Get the return type of all element values , Basically, they are all references to elements , Therefore, the operation of self increase or self decrease can be used , Whether pre or post
- Object oriented programming methods , The most obvious difference between programming and process oriented programming is : Object oriented is “ Take a step , Take a look ” The programming process of , That is, first build the required objects , When some properties or functions are needed, add corresponding programs to realize ; Process oriented is “ Everything is planned ” The programming process of , That is, before writing the program , Just put every variable in the program , Every logical relationship is designed , Then program directly
In the next article , We will introduce C++ In the container ——deque
边栏推荐
- Style transfer -- CCPL: contrast coherence preserving loss for versatile style transfer
- STL notes (II): template and operator overloading
- Anaconda installs jupyter
- Learning records [email protected] R & D effectiveness measurement indicators
- [c language] custom type (structure ~ enumeration ~ Union)
- rhcsa暑假第三天
- PyG搭建GCN实现链接预测
- When image component in wechat applet is used as background picture
- Introduction to CpG control network
- Unity LOD
猜你喜欢

Ownership in rust -- introduction of rust language Xiaobai 11

Pychart configuration pyqt5

Druid connection pool - strong self-study from 0. Those who don't understand Druid can click in. If you know not to click in, you will think I'm wordy

Docker builds MySQL master-slave replication

Solve the problem that uni app applet obtains routes and route parameters

Why does the official not recommend using UUID as MySQL primary key

Forwarding and sharing function of wechat applet

Completed project series Tutorials - smart campus management system
![[untitled]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[untitled]

Zhongchuang computing power won the recognition of "2022 technology-based small and medium-sized enterprises"
随机推荐
HMS core discovery Episode 16 live broadcast preview | play AI's new "sound" state with tiger pier
AUTOSAR from getting started to mastering 100 lectures (105) - protection mechanism of AUTOSAR timing for functional safety
2022-07-24:以下go语言代码输出什么?A:[]int{};B:[]int(nil);C:panic;D:编译错误。 package main import ( “fmt“ ) f
2022-7-13 summary
How can test / development programmers with 5 years of experience break through the technical bottleneck? Common problems in big factories
如何判断是否遭到DDOS攻击
The second day of rhcsa summer vacation
Gbase JDBC connection database exception
1310_一个printf的实现分析
Interviewer: explain the core principle of ThreadLocal
Unity LOD
Event cycle mechanism browser nodejs async await execution sequence promise execution sequence interview questions
Li Kou 731. My schedule II
Delivery practice of private PAAS platform based on cloud native
ESWC 2018 | r-gcn: relational data modeling based on graph convolution network
Seven suggestions for Server Protection
Small case of data analysis: visualize recruitment data and view the most needed technologies in the field~
ESWC 2018 | R-GCN:基于图卷积网络的关系数据建模
956. Highest billboard pressure DP
Web: compiling big refactoring from 10 to 1