求vector的最大值

调用algorithm中的max_elment

1
2
vector<int> num = {......};
int max = *max_element(num.begin(),num.end());

求vector的和

使用numeric中的accumulate

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
#include <numeric> // std::accumulate

int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};

// 第三个参数是初始值,一般设为 0
int sum = std::accumulate(nums.begin(), nums.end(), 0);

std::cout << "Sum = " << sum << std::endl;
return 0;
}

使用getline

调用sstream包的字符串流和fstream的文件输出流

1
2
3
4
5
6
std::ifstream file(file_name);
std::stringstream ss;
type x,y;
while(getline(file,ss)){
ss>>x>>y;
}

使用sort进行排序

下面是一个使用sort对一个vector<pair<int,int>>vector按照第一个元素的大小进行排序的例子

1
2
3
4
vector<pair<int, int>> vec = {{3, 10}, {1, 20}, {4, 15}, {2, 30}};
sort(vec.begin(),vec.end(),[](const pair<int,int> &a ,const pair<int,int> &b){
return a.first > b.first// 按照第一个元素降序排列
})

vector的初始化

std::vector提供了一个可以指定元素个数和初始值的构造函数,函数签名如下,第一个是元素个数,第二个是元素的初始值

1
std::vector<Type> vec(size_t count,const Type& value);

计时

1
2
3
4
5
6
7
8
9
10
#include <chrono>
#include <thread>
int main(){
using namespace std::literals::chrono_literals;//使用“s”
auto start = std::chrono::high_resolution_clock::now();//当前时间
std::this_thread::sleep_for(1s);//程序休眠1s
auto end = std::chrono::high_resolution_clock::now();//当前时间
std::chrono::duration<float> duration = end - start;
std::cout<<duration.count()<<"s"<<std::endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <chrono>
using namespace std;

void some_function() {
for (int i = 0; i < 1000000; ++i) {}
}

int main() {
auto start = chrono::high_resolution_clock::now();

some_function();

auto end = chrono::high_resolution_clock::now();

// 微秒
auto duration_micro = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "Time taken: " << duration_micro.count() << " microseconds" << endl;

// 毫秒
auto duration_milli = chrono::duration_cast<chrono::milliseconds>(end - start);
cout << "Time taken: " << duration_milli.count() << " milliseconds" << endl;

// 秒
auto duration_sec = chrono::duration_cast<chrono::seconds>(end - start);
cout << "Time taken: " << duration_sec.count() << " seconds" << endl;

return 0;
}

查找map中的元素

findfind会根据指定键值进行二分查找,并返回一个迭代器,如果找到该元素,迭代器指向该值,如果找不到,则返回end()

1
2
3
4
5
6
7
8
9
10
11
12
std::map<std::string, int> m;
m["apple"] = 1;
m["banana"] = 2;
m["orange"] = 3;

std::string key = "banana";
auto it = m.find(key);
if (it != m.end()) {
std::cout << "Found: " << it->first << " -> " << it->second << "\n";
} else {
std::cout << key << " not found.\n";
}

count:会返回键在map中出现的次数,0或1

1
2
3
4
5
if (m.count("apple") > 0) {
std::cout << "apple exists in the map.\n";
} else {
std::cout << "apple does not exist in the map.\n";
}