当前位置:网站首页>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
边栏推荐
- Go language function
- Purpose of setting novice task period in the integral system
- Ora-01460: conversion request cannot be implemented or unreasonable
- Zhongchuang computing power won the recognition of "2022 technology-based small and medium-sized enterprises"
- 2022-7-18 summary
- Li Kou 731. My schedule II
- Execution process of NPM run XX
- Which website is suitable for physical server
- rhcsa暑假第三天
- Getting started with scratch
猜你喜欢

When image component in wechat applet is used as background picture
![2022-07-24:以下go语言代码输出什么?A:[]int{};B:[]int(nil);C:panic;D:编译错误。 package main import ( “fmt“ ) f](/img/bf/e38a8fd813f88a83f61a1abfa3b95d.png)
2022-07-24:以下go语言代码输出什么?A:[]int{};B:[]int(nil);C:panic;D:编译错误。 package main import ( “fmt“ ) f

Permanent magnet synchronous motor 36 question (1) -- what is the difference between salient pole motor and salient pole motor?

一篇文章带你读懂Redis的哨兵模式

2、 Mysql database foundation

Special analysis of data security construction in banking industry

Leetcode55. Jumping game

It we media shows off its wealth in a high profile, and is targeted by hacker organizations. It is bound to be imprisoned
![[no title] 1](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[no title] 1

Unity LOD
随机推荐
Baklib: share some methods about building enterprise knowledge management (km)
rhcsa暑假第二天
85 distributed project construction
Novel capture practice
搭建私有CA服务器
Gbase JDBC connection database exception
Unity LOD
nacos中哪边有这个列的sql脚本啊?
教你如何定位不合理的SQL?并优化之
956. Highest billboard pressure DP
1310_一个printf的实现分析
STM32 Development Notes 119: what macros are required to enable FPU?
Pyg builds GCN to realize link prediction
Xiaohongshu joins hands with HMS core to enjoy HD vision and grow grass for a better life
H5 new feature domcontentloaded event - custom attribute -async attribute -history interface method - local storage -postmessage
Set up private CA server
Three must know and know problems of redis
AUTOSAR from getting started to mastering 100 lectures (105) - protection mechanism of AUTOSAR timing for functional safety
How can test / development programmers with 5 years of experience break through the technical bottleneck? Common problems in big factories
Introduction to CpG control network