导航

c++刷题笔记

Posted on 2020-09-10 23:18  wngg  阅读(204)  评论(0)    收藏  举报

// ========== Function ==========//
// 绝对值
abs(a);
// a^b
pow(a, b);
// a^0.5
sqrt(a);
// 边界值
INT_MAX
INT_MIN

// ========== Vector ==========//
// 定义
vector a;
// 尾部增加、删除项
a.push_back(b);
a.pop();
// 在第一项前加入元素,删除第一项,删除第一项到第三项之前的项
a.insert(a.begin(), b);
a.erase(a.begin())
a.erase(a.begin(), a.begin() + 2);
// 排序
sort(a.begin(), a.end());
// 反转
reverse(a.begin(), a.end());

// ========== String ==========//
// 定义
string a = "test";
// 截取,返回从pos下标开始长度n的字符串
string b = a.substr(pos, n);
string b = a.substr(pos);
// 替换
string b = "t";
a.replace(pos, n, b);
// 查找,找不到返回a.npos
a.find(b);
a.rfind(b);
a.find(b, pos);

// ========== Stack ==========//
// 定义,先入后出
stack a;
// 返回、增加到栈顶、删除栈顶
int b = a.top();
a.pop();
a.push(b);
// 判断空、返回元素数
bool b = a.empty();
int b = a.size();

// ========== Queue ==========//
// 定义,先入先出
queue a;
// 返回、删除首项
int b = a.front();
a.pop();
// 返回、增加到尾项
int b = a.back();
a.push(b);
// 判断空、返回元素数
bool b = a.empty();
int b = a.size();

// ========== HashMap ========== //
// 定义
map<string, int> a;
// 插入
a.insert(make_pair<string, int>("key1", 1));
// 修改
a["key1"] = 11;
// 查找(返回迭代器地址,不存在则返回a.end())
auto p_a = a.find("key1");
if (p_a != a.end()) {
cout << p_a->first << endl;
cout << p_a->second << endl;
}
// 删除(也可用迭代器做参数)
a.erase("key1");

// ========== Struct ========== //
struct StructName {
int id;
string name;
};

struct StructName a;
a.id = 0;
a.name = "a";
struct StructName *p_SN = (struct StructName *)malloc(sizeof(struct StructName));

// ========== 字符串切割 ========== //
把长字符串s用子字符串c切割,得到vector v
void SplitString(const string& s, const string& c, vector& v)
{
string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while(string::npos != pos2) {
v.push_back(s.substr(pos1, pos2-pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if(pos1 != s.length())
v.push_back(s.substr(pos1));
}

// ========== vector去重 ========== //
// 先排序,因为unique只操作相邻且相同的元素。greater()参数表示从大到小排序。
std::sort(tmp.begin(), tmp.end(), greater());
// unique会把相邻重复的元素移到最后面,并未删除,因此要保存返回值。
auto new_end = std::unique(tmp.begin(), tmp.end());
// 删除尾部重复的项。
tmp.erase(new_end, tmp.end());

// ========== vector去重 ========== //
// std::vectorstd::string根据std::string长度排序。
std::sort(words.begin(), words.end(), []
(const std::string &first, const std::string &second){
return first.size() < second.size();
});