字符串拼接
- + 拼接, 时间啊空间复杂度均很高, 因为需要重新开辟内存依次合并两个字符串
- push_back(char) 在字符串结尾添加字符
- append(str) 在字符串结尾添加另一个字符串
string s = "";
s+="a";
s.push_back('a');
s.append("dd").append("cc").push_back('a');
cout<<s<<endl;
二叉树数组存储索引
- n为数组中结点下标, m为0-n之间空结点个数
- 当把树存储到数组中时(叶子结点的两个NULL子结点也存储), 父子结点关系如下.
图片来源力扣用户@Krahets
map的使用
class CMP
{
public:
bool operator()(pair<string, int>& p1, pair<string, int>& p2) const
{
if(p1.second == p2.second)
return p1.first < p2.first;
return p1.second > p2.second;
}
};
int main()
{
// map只能针对key进行排序, 不能针对value进行排序. 同时仿函数重载()运算符需要时const
// map<string, int, CMP> mp // CMP重载的参数应该是string, 不应该死pair
map<string, int> mp;
mp["i"]++;
mp["love"]++;
mp["leetcode"]++;
mp["i"]++;
mp["love"]++;
mp["coding"]++;
mp["am"]++;
// map 的迭代器不是随机存取迭代器, 不能进行+-操作, 因此不能用sort排序
// sort(mp.begin(), mp.end(), CMP());
for(auto p : mp)
cout<<p.first<<" "<<p.second<<endl;
return 0;
}
字符转字符串
char letter = 'a';
string s = to_string(letter); //97 因为to_string接收数字, 把数字转换为字符串, 字符会先转换为ASCII
// 两种正确的方法
string str(1, letter);
string str; str.push_back(letter);