C++---实用编程技巧记录
注:为了写出高质量的代码,一些简单的逻辑尽量用库函数去实现,减少代码量;
1. 求最小值/最大值
- 普通vector 求最小值
std::vector<double> x={0,2,3,7,4,1};
auto min_inter = std::min_element(x.begin(), x.end());
double min= *min_inter; // 值
int index = std::distance(x.begin(),min_inter); //索引
- map或者vector 根据需要根据某一维度数值获得最大最小值
// 使用lambda表达式
std::vector<cv::Point2f> pts;
auto compare_x = [](const cv::Point2f &p0, const cv::Point2f &p1) -> bool {
return (p0.x < p1.x);
};
auto min_inter = std::min_element(pts.begin(), pts.end(),compare_x);
cv::Point2f min= *min_inter; // 值
int index = std::distance(pts.begin(),min_inter); //索引
以上当然可以直接进行排序,使用 sort函数
2. 排序
std::vector<cv::Point2f> pts;
// 升序
auto sort_x = [](const cv::Point2f &p0, const cv::Point2f &p1) -> bool {
return (p0.x < p1.x);
};
std::sort(pts.begin(), pts.end(), sort_x);
lambda表达式 简写版:
std::sort(pts.begin(), pts.end(), [](const cv::Point2f &p0, const cv::Point2f &p1) {return p0.x < p1.x;});
3. 均值
double mean_ms = std::accumulate(std::begin(all_times),
std::end(all_times), 0.0) /
all_times.size();
4 lambda 与多线程
4.1 多线程(类函数)
买东西 :
class MyClassTest() {
bool Buy(std::string type, int money) {
// do something
for (int i = 0; i < 10; ++i) {
std::cout << "now is buy : " << type << std::endl;
}
return true;
}
bool RunMultiBuy() {
auto buy_thread_0 =
std::make_shared<std::thread>(&MyClassTest::Buy, this, "book", 20);
buy_thread_0->join();
auto buy_thread_1 =
std::make_shared<std::thread>(&MyClassTest::Buy, this, "pen", 10);
buy_thread_1->join();
}
}
4.2 多线程(使用lambda)
买东西 :
class MyClassTest() {
bool RunMultiBuy() {
// lambda 已获取 this
auto buy = [this](std::string type, int money) {
// do something
for (int i = 0; i < 10; ++i) {
std::cout << "now is buy : " << type << std::endl;
}
return true;
};
auto buy_thread_0 = std::make_shared<std::thread>(buy, "book", 20);
buy_thread_0->join();
auto buy_thread_1 = std::make_shared<std::thread>(buy, "pen", 10);
buy_thread_1->join();
}
}
5. 查找
map 根据value 查找 key
const std::map<std::string, int> str_id_map = {
{
"jack", 23424}, {
"tom", 12533}, {
"hopo", 5496}};
int id = 12533;
std::string name = "";
const auto& str_map = str_id_map;
auto iter =
std::find_if(str_map.begin(), str_map.end(),
[id](const auto& item) {
return item.second == id; });
if (iter != str_map.end()) {
name = iter->first;
}
6. 对数组根据某个值进行分段
- 包含对数据的打印
- 对分段使用库函数处理
#include <algorithm>
#include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &out, const std::vector<T> &ve) {
out << "[";
std::string delimiter = "\0";
for (auto &item : ve) {
out << delimiter << item;
delimiter = ",";
}
out << "]\n";
return out;
}
int main() {
std::vector<int> points{
1, 2, 3, 6};
int cut_x = 6;
auto iter =
std::find_if(points.begin(), points.end(),
[&cut_x](const auto &val) {
return val >= cut_x; });
std::vector<int> points_1, points_2;
if (iter == points.begin()) {
points_2 = points;
} else if (iter == points.end() || std::next(