Basic knowledge of C++--First introduction to Vector container

The basics of STL in C++ -- the first knowledge of vector
We have learned the content of static arrays before. The disadvantage of static arrays is that once initialized, the size of the array cannot be changed, but dynamic arrays do not have this problem. Dynamic arrays (vector containers) are needed When expanding the size, it will automatically handle its own storage requirements. That is to say, the vector container will automatically adjust its own size according to the added elements. To use the vector container, you need to declare the header
file #include<vector>
vector uses the format vector< typename> variable

#include <iostream>
#include <vector>

using namespace std;

int main() {

    vector<int> vec;
    int i = 0;
    cout << "vector_size:" << vec.size() << endl;
    for (i; i < 6; i++) {
        vec.push_back(i + 1);
    }
    cout << "vector_expand_num:" << vec.size() << endl;
    for (i; i >= 0; i--) {
        cout << "get_vec_value:" << vec[i] << endl;
    }
    
    for(vector<int>::iterator v = vec.begin(); v != vec.end(),v++) 
    {
        cout << "v_value:" << *v << endl;
    }
    return 0;
}
输出:
vector_size:0
vector_expand_num:6
get_vec_value:17367376
get_vec_value:6
get_vec_value:5
get_vec_value:4
get_vec_value:3
get_vec_value:2
get_vec_value:1
v_value:1
v_value:2
v_value:3
v_value:4
v_value:5
v_value:6

push_back():Add data to the end of the container
vector.size(): Get the size of the container
vector.begin(): Iterator pointing to the head of the container
vector.end(): Iterator pointing to the end of the container
Let’s look at the usage of strings

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> str;
    str.push_back("www");
    str.push_back(".baidu");
    str.push_back(".com");
    for (vector<string>::iterator iter = str.begin(); iter != str.end(); ++iter) {
        cout << *iter;
    }
    return 0;
}

Function introduction
at(idx) returns the data pointed to by index idx. If idx is out of bounds, out_of_range is thrown.
back() returns the last element without checking whether the data exists.
front() returns the first element.
swap() swaps two Vectors.
pop_back() It removes the last element from the vector.
empty() determines whether the Vector is empty (empty when true is returned)
insert() It will insert a new element at the specified position.
erase() deletes the specified element.
resize() It modifies the size of a vector.
clear() It removes all elements from the vector.
size() returns the size of the number of elements in the Vector.

str.erase(str.begin() + 1);//删除下标为1的元素
str.insert(str.begin() + 2, "123");//在下标为2的位置插入元素
str.pop_back();//删除尾部的元素
str.resize(10);//改变容器的大小
str.at(0);//返回下标为0的元素
str.back();//返回尾部元素
str.front();//返回头部元素

Guess you like

Origin blog.csdn.net/weixin_50016546/article/details/131513773