c++基础语法 --STL

STL

STL 六大组件

  • 容器、算法、迭代器、仿函数、适配器、空间配置器

容器

  • 序列容器 (线性结构): Deque、list、vector
  • 关联式容器 (非线性结构):Set、multiset、Map、multimap
常用容器
string
// 构造
 string s1 = string();
    // 通过字符串构造
    string s2 = string(s1);// 相当于""
    char* array = "Hello world ! !";
    // 通过字符数组构造
    string s3 = string(array);
// 赋值
 string s1 = string();
    string s2 = "hello world! !!";
    s1 = s2;// 用=赋值
    cout<<s1<<endl;
    char* arr = "abc";
    s2 = arr;// 用数组赋值
    cout<<s2<<endl;
    string s3 =s1;
    s3 = 'a';// 用字符赋值
    cout<<s3<<endl;
用assgin函数也可以实现上面的效果
asssgin(string)
assgin(int,char)例: s1.assgin(3,‘a’);// 相当于 s1 = “aaa”;
assgin(char*)相当于 = char*;
// 使用返回的引用改变数组
    string s1 = "hello world! !!";
    char& c = s1[2];
    cout<<s1<<endl; // hello world! !!
    c = 'a';
    cout<<s1<<endl;//healo world! !!
    // 当内存重新分配时在使用原来引用可能会又出错的风险
    s1 = "123456789010";// 长度比之前长,内存被重新分配
    cout<<(int*)(s1.c_str())<<endl;// c_str 将字符串转为c风格的字符串数组
append追加
append(string)
append(string, int )拼接前那个
append(string, int a, int b)从第a个开始拼接后面b个字符
append(int n, char c)追加n个c
compare(比较)、insert(插入)、erase(删除)
compare(string)比较两个字符串
substr(pos, len)从第pos位截取len位字符,截取的字符串对字符串本身没有影响string s1 = “hello world! !!”;cout<<s1.substr(2, 5)<<endl;// 打印llo w
earase(pos, len)从下标pos开始删除len个字符string s1 = “hello world! !!”;s1.insert(2, 3,‘a’);cout<<s1<<endl;s1.erase(2, 3);cout<<s1<<endl;
insert(pos, len, str)从pos开始插入
vector
  • 和array区别在于,前者是动态空间,array在被创建时大小已经被确定。vector采用效率更高的算法管理内存,方便程序员管理。
  • 提供的是随机访问的迭代器
  • 迭代器:begin()指向首元素指针 end()指向最后一位元素的下一位
// 1. 引入vector容器
#include<vector>
using namespace std;

int main(){
    // 2. 创建vector容器
    vector<int> v;
    // 3. 添加元素
    for (int i = 0; i < 20; i++)
        v.push_back(i);
        // 使用迭代器遍历容器
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
        cout<<*it<<endl;
        // 使用迭代器修改元素
        *it *= 10;
    }
    // 缩写
    for (int it : v) {
        cout<<it<<endl;
    }
    // 倒序
    for (vector<int>::iterator it = v.end() - 1; it != v.begin() - 1; it--) {
        cout<< *it<< endl;
    }
    cout<<v.size()<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值