目录

(1)vector说明

(2)vector对象的构造

(3)容器接口

1.全部接口说明表

2.应用举例

删除值为指定值的所有元素

获取值在vector中的下标位置

用for + auto 遍历vector

(4)vector与算法

使用find查找元素的位置

使用reverse将元素翻转

使用sort排序

使用copy复制替换


(1)vector说明

在C++中,vector是一个十分有用的容器,是一个能够存放任意类型的动态数组,能够增加和压缩数据。

vector的元素不仅仅可以是int、double、string,还可以是结构体,但是要注意:结构体要定义为全局的,否则会出错。

vector是STL的动态数组,可以在运行中根据需要改变数组的大小。

因为它以数组的形式储存,所以它的内存空间是连续的。

与数组相比,容器在自动处理容量的大小时会消耗更多的内存,但能很好的调整存储空间大小。

优缺点:随机访问快(O(1)),尾部插入/删除高效(O(1)),中间插入/删除慢(O(n))。需要频繁随机访问的场景(如矩阵运算)。

(2)vector对象的构造

// 创建一个vector,数据类型为int,默认空间容量为0,默认初值为0
vector<int> a            
std::vector<int> vec1;

// 创建指定个数的vector
vetcor<int> a(100)          //定义100个值为0的元素     
std::vector<int> vec2(4);     //定义4个值为0的元素       
vector<int> a(100, 6)              //定义100个值为6的元素
std::vector<int> vec3(4, 10);      // 4个值为10的vector [10 10 10 10]
vector<string> a(10, "null")       //定义10个值为null的元素
vector<string> a(10, "hello")      //定义10个值为hello的元素


// 给定指定初始数据
std::vector<int> vec6 = {10, 20, 30, 40}; 


// 拷贝构造(全部拷贝)
vector<int> b(a)                  
std::vector<int> vec5(vec3);    

//  拷贝构造(部分拷贝)
vector<string> b(a.begin(),a.end())      
std::vector<int> vec4(vec3.begin(),vec3.end());  


// 将map的键值对(string -> int) pair<string, int> 拷贝到vector中
std::vector<pair<string, int>> vec_key_value(data_map.begin(), data_map.end())


// 把a中的从a.begin()(包括它)到a.end()(不包括它)的元素复制到b中,
// 从b.begin()+1的位置(包括它)开始复制,覆盖掉原有元素
#include <algorithm>
copy(a.begin(),a.end(),b.begin()+1); 

(3)容器接口

1.全部接口说明表

操作

操作示例

创建对象

vector<int> array;

尾部插入元素

array.push_back(0);

删除向量的最后一个元素

array.pop_back();

返回最后一个元素

int x = array.back();

返回第一个元素

x = array.front();

使用下标访问元素

cout << array[0] << endl;

根据下标修改值

array[1] = 100;

使用迭代器访问元素

vector<int>::iterator it;

for (it = array.begin(); it != array.end(); it++)

cout << *it << endl;

在第i个元素处插入a,之前i及i后面的元素后移;

array.insert(array.begin()+i,a);

删除元素 // 注意只删除首次出现的那个值

array.erase(array.begin() + 3);

//当删除迭代器所指向的元素的时候,erase删除函数会返回下一个迭代器的位置

it = data.erase(it);

删除区间(左闭右开)

array.erase(array.begin() + 2, array.end() - 1);

获取array长度

unsigned int len = array.size();

清空

array.clear();

判断是否为空

if (array.empty())

返回内存中总共可以容纳的元素个数

int x = array.capacity();

扩充容量

    array.reserve(100);

    x = array.capacity();

    cout << x << endl; // 100

调整元素个数

array.resize(10); // 将array的现有元素个数调至10个,多则删,少则补,其值随机

array.resize(10, 99); // 将array的现有元素个数调至10个,多则删,少则补,其值为99

两向量内容交换

array.swap(array2);

// 类似于a和b值互换

向量的比较

向量的比较操作 == != >= <= > <

    bool result = array == array2;

    result = array < array2;

2.应用举例

删除值为指定值的所有元素

#include <iostream>
#include <vector>
using namespace std;

void printV(vector<int> v)
{
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;
}

int main()
{
    vector<int> data = {5, 2, 7, 2, 9, 10};
    printV(data);  // 5 2 7 2 9 10

    vector<int>::iterator it;
    for (it = data.begin(); it != data.end();)
    {
        if (*it == 2)
        {
            // 当删除迭代器所指向的元素的时候,
            // erase删除函数会返回下一个迭代器的位置
            it = data.erase(it);  
        }
        else
        {
            it++;
        }
    }

    printV(data);  // 5 7 9 10

    return 0;

}

获取值在vector中的下标位置

#include <iostream>
using namespace std;
#include <vector>

int array_find(vector<int> array, int value)
{
    vector<int>::iterator it;
    int len = array.size();
    if (len == 0)
    {
        return -1;
    }
    for (int i = 0; i < len; i++)
    {
        if (array[i] == value)
        {
            return i;
        }
    }
    return -2;
}


int main()
{
    vector<int> array;
    cout << array_find(array, 10) << endl;  // -1

    array.push_back(99);
    array.push_back(23);
    array.push_back(10);
    cout << array_find(array, 10) << endl;  // 2

    return 0;
}

用for + auto 遍历vector

#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

void test01()
{
    string s1;                  // 默认初始化,s1是一个空的字符串
    string s2(s1);              // 拷贝构造
    string s3 = s2;             // 赋值构造
    string s4("4444");          // "4444"
    string s5 = "5555";         // 拷贝初始化,同上
    string s6(4, '6');          // 初始化n个字符'6‘串成的字符串
    string s7 = string(4, '7'); // 拷贝初始化,同上

    s1.assign(s6);
    s2 = "2222";

    vector<string> vecStr{s1, s2, s3, s4, s5, s6, s7};
    for (const auto &value : vecStr) {
        cout << "sddress:" << &value << "  value:" << value << endl;
    }
}

int main()
{
    ::test01();
    return 0;
}

(4)vector与算法

使用find查找元素的位置

find(a.begin(),a.end(),10); 

在a中的从a.begin()(包括它)到a.end()(不包括它)的元素中查找10,若存在返回其在向量中的位置。若不存在a.end()。

find的代码原型如下,该函数返回一个迭代器到范围[first,last)中等于val的第一个元素。如果没有找到这样的元素,函数将返回last。函数使用运算符==将各个元素与val进行比较。

template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;

使用例子

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>  //find函数需要此头文件

int main()
{
    vector<int> array;
    array.push_back(10);

    cout << array.size() << endl; // 1
    cout << array[0] << endl; //10

    array.push_back(9);
    array.push_back(10);
    
    vector<int>::iterator it;
    // 返回迭代器位置
    it = find(array.begin(), array.end(), 99);
    // 打印对应的值
    cout << *it << endl;    // 0

    // 返回迭代器位置
    it = find(array.begin(), array.end(), 10);  
    // 打印对应的值
    cout << *it << endl;    // 10

    return 0;
}

使用reverse将元素翻转

在 C++ STL 中,std::reverse 是一个用于反转序列容器中元素顺序的算法,定义在 <algorithm> 头文件中。它适用于支持随机访问迭代器的容器(如 vector、deque、普通数组等)。

#include <algorithm> // 必须包含此头文件
#include <vector>
#include <iostream>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // 反转整个容器
    std::reverse(vec.begin(), vec.end());

    // 输出结果:5 4 3 2 1
    for (int num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // 只反转前3个元素(范围:[vec.begin(), vec.begin() + 3))
    std::reverse(vec.begin(), vec.begin() + 3);
    // 输出结果:3 4 5 2 1
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

使用sort排序

在 C++ STL 中,std::sort 是一个高效的排序算法,用于对支持随机访问迭代器的容器(如 std::vector、std::deque、普通数组等)进行排序。它定义在 <algorithm> 头文件中,默认使用 < 运算符比较元素,但也可以自定义比较函数。

默认升序:sort(array.begin(), array.end());

自定义排序规则:sort(array.begin(),array.end(), Comp);

其中Comp为自定义的排序函数,按什么规则排序,如下面这个例子,返回True表示不交换a和b,返回False表示交换a和b

#include <algorithm>

bool Comp(const int &a, const int &b)
{
    bool ret = a > b;
    return ret; // 为True时不交换a和b,也就是降序排序
}

可以通过传递一个比较函数或 Lambda 表达式来实现降序或其他自定义排序规则。

例子1:降序排序

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> vec = {5, 2, 9, 1, 5, 6};

    // 降序排序
    std::sort(vec.begin(), vec.end(), [](int a, int b) {
        return a > b; // 如果 a > b,则 a 排在 b 前面
    });

    // 输出结果:9 6 5 5 2 1
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

例子2:自定义结构体排序

#include <algorithm>
#include <vector>
#include <iostream>
#include <string>

struct Person {
    std::string name;
    int age;
};

bool comp(const Person& a, const Person& b)
{
    // 先按年龄升序
    if (a.age != b.age) {
        return a.age < b.age;
    } 
    
    // 若年龄相同,则按名字叫降序
    return a.name > b.name; 
}

int main() {
    std::vector<Person> people = {
        {"Alice", 25},
        {"Bob", 20},
        {"Charlie", 30},
        {"Blice", 25},
    };

    // 按年龄升序排序
    std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
        return a.age < b.age;
    });

    // 输出结果:
    // Bob (20), Alice (25), Blice (25), Charlie (30), 
    for (const auto& p : people) {
        std::cout << p.name << " (" << p.age << "), ";
    }
    std::cout << std::endl;

    // 先按年龄升序, 若年龄相同,则按名字叫降序
    // Bob (20), Blice (25), Alice (25), Charlie (30),
    std::sort(people.begin(), people.end(), comp);
    for (const auto& p : people) {
        std::cout << p.name << " (" << p.age << "), ";
    }


    return 0;
}

使用copy复制替换

#include <algorithm>

copy(a.begin(),a.end(),b.begin()+1); 
// 把a中的从a.begin()(包括它)到a.end()(不包括它)的元素复制到b中,
// 从b.begin()+1的位置(包括它)开始复制,覆盖掉原有元素


end 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐