一些写leetcode的笔记

  1. 标准库中的string类没有实现像C#和Java中string类的split函数,所以想要分割字符串的时候需要我们自己手动实现。但是有了stringstream类就可以很容易的实现,stringstream默认遇到空格、tab、回车换行会停止字节流输出。
#include <sstream>
#include <iostream>
 
int main()
{
   
   
	std::stringstream ss("this apple is sweet");
	std::string word;
	while (ss >> word)
	{
   
   
		std::cout << word << std::endl;   // 这里依次输出this、apple、is、sweet四个单词
	}
 
    return 0;
}
  1. 可以使用getline()函数用其他字符分割字符串,第一个参数 - 流中获取数据,第二个参数 - 把数据转换成字符串,第三个参数 - 分隔符。
#include <sstream>
#include <iostream>
 
int main()
{
   
   
    std::string str = "this,is,apple";
	std::istringstream ss(str);
	std::string token;
 
	while (std::getline(ss, token, ',')) {
   
   
		std::cout << token << '\n';        // 这里依次输出this、is、apple三个单词
	}
 
    return 0;
}
  1. 匿名函数实现一个功能,输入一个由空格分割单词的字符串,就计算出每个单词的出现频率:
unordered_map<string, int> freq;
        
        auto insert = [&](string s) {
   
   
            stringstream ss(s);
            string word;
            while (ss >> word) {
   
   
                ++freq[move(word)];
            }
        };

        insert(s1);
  1. accumulate是numeric库中的一个函数,主要用来对指定范围内元素求和,但也自行指定一些其他操作,如范围内所有元素相乘、相除等。
int main() {
   
   
    vector<int> arr{
   
   1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int sum = accumulate(arr.begin(), arr.end(), 0); // 初值0 + (1 + 2 + 3 + 4 +... + 10)
		int sum = accumulate(arr.begin()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值