当前位置:网站首页>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
边栏推荐
- STM32 Development Notes 118: using CMSIS DSP Library in stm32cube IDE
- [small program practice] first day
- nacos中哪边有这个列的sql脚本啊?
- Etcd learning
- unity 3D物体添加 点击事件
- The 6th "Blue Hat Cup" National College Students' Cyber Security Skills Competition writeup
- 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
- Summary and Prospect of aut, the transport layer protocol of sound network -- dev for dev column
- 学习记录[email protected]研发效能度量指标
猜你喜欢

1310_一个printf的实现分析

Three must know and know problems of redis

rhce第一天

rhcsa暑假第三天

Special analysis of data security construction in banking industry

If you don't know these 20 classic redis interview questions, don't go to the interview!
![2022-07-24: what is the output of the following go language code? A:[]int{}; B:[]int(nil); C:panic; D: Compilation error. package main import ( “fmt“ ) f](/img/bf/e38a8fd813f88a83f61a1abfa3b95d.png)
2022-07-24: what is the output of the following go language code? A:[]int{}; B:[]int(nil); C:panic; D: Compilation error. package main import ( “fmt“ ) f

rhcsa暑假第二天

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

OA and fansoft Bi cross system users, departments and posts synchronous summary
随机推荐
This low code reporting tool is needed for data analysis
Web: compiling big refactoring from 10 to 1
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
Introduction to CpG control network
Baklib: share some methods about building enterprise knowledge management (km)
Style transfer -- CCPL: contrast coherence preserving loss for versatile style transfer
Gbase 8A about no suitable driver
MCU experiment record
Gbase JDBC connection database exception
Sword finger offer II 014. anagrams in strings
[sht30 temperature and humidity display based on STM32F103]
AUTOSAR from getting started to mastering 100 lectures (105) - protection mechanism of AUTOSAR timing for functional safety
绕过 Web 应用程序中的 XSS 过滤器
unity 3D物体添加 点击事件
Xiaohongshu joins hands with HMS core to enjoy HD vision and grow grass for a better life
Implementation principle of epoll
【微信小程序】拍卖商品详情页设计与交互实现(包含倒计时、实时更新出价)
Set up private CA server
Li Kou 731. My schedule II
Oracle split branches