栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

C++ STL入门(持续更新中)

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ STL入门(持续更新中)

一、vector变长数组 1.读入方法
#include 
#include 

using namespace std;
int main(){
    vector a;//直接读入一个名为a的vector
    vector a(10);//读入一个长为10的名为a的vector
    vector a(10, 2);//读入一个长为10的,每个数都为2的名为a的vector
    vector a[10];//读入10个vector
}
2.容器自带函数

部分函数如下:

#include 
#include 

using namespace std;
int main(){
    vector a;//直接读入一个名为a的vector
    a.size();//a的元素个数,O(1)
    a.empty();//a是否为空,是返回true,否返回false,O(1)
    a.clear();//清空(队列没有)
    a.front();//返回首位元素
    a.back();//返回末位元素
    a.push_back();//在末尾插入新数
    a.pop_back();//删掉末位元素
    a.begin();//迭代器首位
    a.end();//迭代器末位的下一位
}
3、迭代器

迭代器it可视为指针,*it为地址为it的数值,利用迭代器遍历一个vector方法如下:

#include 
#include 

using namespace std;

int main() {
    vector a;//直接读入一个名为a的vector
    for (int i = 0; i < 10; i++) a.push_back(i);
    vector::iterator it;//迭代器
    for (it = a.begin(); it != a.end(); it++) cout << *it << " ";
    cout << endl;
    return 0;
}
4.C++11的新特性auto

auto可以自动识别变量的类型,适合类型很长的变量(如迭代器)的声明,还可用于for循环遍历,格式为for(auto x: a),代码如下:

#include 
#include 

using namespace std;

int main() {
    vector a;//直接读入一个名为a的vector
    for (int i = 0; i < 10; i++) a.push_back(i);
    for (auto it = a.begin(); it != a.end(); it++) cout << *it << " ";
    cout << endl;
    for(auto x : a) cout << x << " ";
    cout << endl;
    return 0;
}
5.其他

系统为某一程序分配空间时,所需时间与空间大小无关,而与申请次数有关。

举个例子,你申请一个长度为1的vector和长度为100的vector所用时间是一样的,而你申请1000遍长度为1的vector时间是申请一次长度为1000的vector的时间的1000倍!

所以,我们要尽量减少申请vector的次数!

同时,vector还可以比较大小,按照的是字典序。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/334607.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号