collection

1.

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
30
31
32
33
34
35
36
37
38
39
#include <algorithm>
#include <iostream>
#include <vector>

struct PriceInfo { double price; };

int main()
{
const std::vector<int> data {1, 2, 4, 5, 5, 6};

for (int i = 0; i < 7; ++i)
{
// Search first element that is greater than i
auto upper = std::upper_bound(data.begin(), data.end(), i);

std::cout << i << " < ";
upper != data.end()
? std::cout << *upper << " at index " << std::distance(data.begin(), upper)
: std::cout << "not found";
std::cout << '\n';
}

std::vector<PriceInfo> prices {{100.0}, {101.5}, {102.5}, {102.5}, {107.3}};

for (double to_find : {102.5, 110.2})
{
auto prc_info = std::lower_bound(prices.begin(), prices.end(), to_find,
[](double va,const PriceInfo& info)
// no known conversion for argument 1 from 'PriceInfo' to 'double'
{
return va > info.price;
});

prc_info != prices.end()
? std::cout << prc_info->price << " at index " << prc_info - prices.begin()
: std::cout << to_find << " not found";
std::cout << '\n';
}
}
需要将lambda函数 捕获列表中参数位置互换
1
2
3
4
5
auto prc_info = std::lower_bound(prices.begin(), prices.end(), to_find,
[](const PriceInfo& info, double va)
{
return va > info.price;
});

2.

1
2
3
4
5
6
7
8
9
10
11
12
// 修改时间
char* t = ctime(&st.st_mtime); // 这个字符串包含最后的换行符
// printf("%s\n", t);

char* tt;
strncpy(tt, t, strlen(t) - 1); // 发生段错误

char tt[1024];
// strncpy(tt, t, sizeof(t) - 1); // Tue May
strncpy(tt, t, strlen(t) - 1); // Tue May 2 10:15:54 2023
printf("%s\n", tt);

`dest`不能用`char*`的`tt`,只能用`char tt[1024]`;

sizeof只有前半段字符串,strlen才能全部复制

并且char tt[1024]会改变前面变量quanxian的值,在后面加上了tt,而修改成更大的值则正常

3.


collection
https://kevin346-sc.github.io/2023/04/19/collection/
作者
Kevin Huang
发布于
2023年4月19日
许可协议