PAT乙级(CPP基础&STL)

万能头,库

#include

string数组

//string的初始化
string s="abc";
string(6,'A');
//string取子串(起始位置,长度)
string s="Hello World!"; 
cout << s.substr(6) << endl; //从第6位开始取字符,即从W开始
cout << s.substr(6,2) << endl; //从第6位开始取2个字符
s.replace(2,5,"XXXX");//string替换(起始位置,长度,替换字符)
s.erase(0,2); //string的删除(起始位置,长度)*也可以用replace实现
s.c_str();//string转化成字符串

vector动态数组

vector data;
data.push_back(1);
cout << data.size();
vector v(10);//定义长度为10的int数组,默认10个元素均为0

vector v;
v.resize(8);//先定义,后将长度设置为8,默认元素都为0

vector v(100,9);//定义+初始化,元素值均为9
for(int i=0; i < v.size(); i++)//下标遍历

for(vector::iterator i = v.begin(); i != v.end(); i++) //迭代器遍历

for(auto i=A.begin(); i!=A.end(); i++)
    cout << *i << endl;

清空数组 

s.clear()

set集合(要求有序)

set s
s.insert(1);

//查询集合内的元素
if(s.find(5) != s.end()){
    cout << "yes" << endl;
}

set 具有天然的排序与去重功能,结构体不是基本类型(基本类型有默认的排序准则),因此需要重载 < 运算符。(相当于给自定义类型一个排序准则)。bool operator < (const HolePos & a)const ;运算符重载必须是const。

#include
#include
#include
using namespace std;

struct stu {
    string name;
    string id;
    int sco;
    bool operator < (const stu & a)const {
        return id < a.id;
    }
};
int main()
{
    set s;
    s.insert(stu{ "214820413","xyq",50 });
    s.insert(stu{ "214820414","yjw",70 });
    for (auto i = s.begin();i != s.end();i++)
    {
        cout << i->name << " " << i->id << " " << i->sco << endl;
    }
    return 0;
}

map键值对,映射

#include
#include
using namespace std;

int main()
{
    mapm = {
        {"id1",60},{"id2",70}
    };
    cout << m["id1"] << endl;
    cout << m["id2"] << endl;
    return 0;
}

map遍历 

for (auto i = m.begin(); i != m.end();i++)
    {
        cout << i->first << " " << i->second << endl;
    }

sort函数

#include
int A[] = { 5,2,6,7,4,1,3 };
sort(A, A+7);
for (int i = 0; i < 7; i++)
    cout << A[i] << " ";
vector A;
sort(A.begin(),A.end());

cmp函数调用 

#include
#include
#include
using namespace std;

struct stu {
    int score;
    string id;
};

bool cmp(stu a, stu b)
{
    if (a.score == b.score)
        return a.id < b.id;
    return a.score < b.score;
}
int main()
{
    vector L;
    L.push_back(stu{ 50,"ccc" });
    L.push_back(stu{ 50,"bbb" });
    L.push_back(stu{ 60,"aaa" });
    sort(L.begin(), L.end(),cmp);
    for (int i = 0; i < L.size(); i++)
        cout << L[i].id << " " << L[i].score << endl;

    return 0;
}

折半查找lower_bound和upper_bound,注意排序

#include
#include
using namespace std;

int main() {
	int num[6] = { 1,2,4,7,15,34 };
	sort(num, num + 6);                           //按从小到大排序 
	int pos1 = lower_bound(num, num + 6, 7) - num;    //返回数组中第一个大于或等于被查数的值 
	int pos2 = upper_bound(num, num + 6, 7) - num;    //返回数组中第一个大于被查数的值
	cout << pos1 << " " << num[pos1] << endl;
	cout << pos2 << " " << num[pos2] << endl;
	return 0;
}

转换 to_string, stoi & stod

string s1 = to_string(123);//把数字转化为string
stoi("123");//把string转换为int

你可能感兴趣的:(c++,开发语言)