C++ tricks For Reference

std::bind

#include <functional>
#include <iostream>
#include <string>
void func(int i, char c, int j, std::string s, int k) {
  std::cout << i << " " << c << " " << j << " " << s << " " << k << std::endl;
}
int main() {
  auto f = std::bind(func, 1, 'c', std::placeholders::_1, std::string("hello"),
                     std::placeholders::_2);
  f(10, 20);
  f(101, 50);
  return 0;
}
/* 输出:
1 c 10 hello 20
1 c 101 hello 50

abi::__cxa_demangle 返回类的名字字符串

下面这个Point一个默认构造的实现参考了下 protobuf 的 pb.cc

#include <cxxabi.h>
#include <iostream>
#include <typeinfo>
class Point {
 public:
  Point() {
    std::cout << "Point()" << std::endl;
    memset(&x, 0, static_cast<size_t>(reinterpret_cast<char*>(&y) -
                                      reinterpret_cast<char*>(&x) + sizeof(y)));
  }
  Point(int _x = 0, int _y = 0) : x(_x), y(_y) {
    std::cout << "Point(int _x = 0, int _y = 0)" << std::endl;
  }
  ~Point() { std::cout << "~Point()" << std::endl; }

  void print() { std::cout << " (" << x << " , " << y << ") " << std::endl; }
  int x;
  int y;

  std::string GetTypeName() {
    return abi::__cxa_demangle(typeid(*this).name(), 0, 0, 0);
  }
};

文件读写

 1. 判断文件是否存在

int main(){
  std::string name="az.txt";
  std::ifstream f(name.c_str());
  if(f.good()){
    std::cout<<"yes"<<std::endl;
  }
  else{
    std::cout<<"no"<<std::endl;
  }
  f.close();

  return 0;
}
int main()
{

  std::ofstream ofs;
  ofs.open("test.txt",std::ios::trunc);

  for(int i=0;i<=20;++i)
  {
    ofs<<i<<": there\n";
  }
  ofs.close();

  return 0;
}

2.  逐行读取文件

int main()
{
  std::string line;
  std::ifstream ifs;
  ifs.open("a.txt",std::ios::in);
  if(ifs.fail()){
    std::cout<<"fail to open fail a.txt"<<std::endl;
  }else{
    while (getline(ifs,line))
    {
       std::cout<<"line: "<<line<<std::endl;
      std::cout<<"line.size: "<<line.size()<<std::endl;
    }
  }
  ifs.close();

  return 0;
}

3. 创建文件并写入

int main()
{

  std::ofstream ofs;
  ofs.open("test.txt",std::ios::trunc);

  for(int i=0;i<=20;++i)
  {
    ofs<<i<<": there\n";
  }
  ofs.close();
  return 0;
}

字符流


  std::string str;
  uint8_t arr[3]={'a','c','z'};
  for (int i = 0; i < 3; ++i) {
    std::cout<<i<<": "<<arr[i]<<std::endl;
    std::ostringstream os;
    os << arr[i];
    str += os.str();
  }
  std::cout<<"str: "<<str<<">"<<std::endl;

优先级队列

priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.A user-provided Compare can be supplied to change the ordering, e.g. using std::greater<T> would cause the smallest element to appear as the top().

优先级队列是容器适配器,可常数时间内查询最大元素(默认),当然用户提供Compare改变其顺序,如使用 std::greator<T> 可以让top() 返回最小值。

leetcode 给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。

class Solution {
public:
    //小顶堆
    class  comp{
        public:
        bool operator()(const std::pair<int,int>& lhs,const std::pair<int,int>& rhs){
            return lhs.second>rhs.second;
        }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        std::unordered_map<int,int> mps;
        for(const auto  elem : nums){
            ++mps[elem];
        }

        std::priority_queue<std::pair<int,int>,std::vector<std::pair<int,int>>,comp> priq;
        for(const auto elem:mps){
            priq.push(elem);
            if(priq.size()>k) priq.pop();
        }

        std::vector<int> res;
        res.resize(k);
        for(int i = k-1;i>=0;--i){
            res[i] = priq.top().first;
            priq.pop();
        }

        return res;
    }
};

基于比较运算符重载的优先级队列

#include <fstream>
#include <iostream>
#include <queue>
#include <vector>

struct Node {
  int size;
  int price;
  bool operator<(const Node &b) const {
    return this->size == b.size ? this->price > b.price : this->size < b.size;
  }
};
class Cmp {
public:
  bool operator()(const Node &a, const Node &b) {
    return a.size == b.size ? a.price > b.price : a.size < b.size;
  }
};

int main() {
  std::priority_queue<Node, std::vector<Node>> priorityQueue;
  for (int i = 0; i < 5; i++) {
    priorityQueue.push(Node{i, 5 - i});
  }
  priorityQueue.push(Node{4, 0});

  while (!priorityQueue.empty()) {
    Node top = priorityQueue.top();
    std::cout << "size:" << top.size << " price:" << top.price << std::endl;
    priorityQueue.pop();
  }
  return 0;
}

/* 输出size的递减序列,size相同的price递增序列
size:4 price:0
size:4 price:1
size:3 price:2
size:2 price:3
size:1 price:4
size:0 price:5

如果改成 this->size > b.size; 输出为递增序列
size:0 price:5
size:1 price:4
size:2 price:3
size:3 price:2
size:4 price:0
size:4 price:1

基于函数对象的优先级队列:

#include <fstream>
#include <iostream>
#include <queue>
#include <vector>

struct Node {
  int size;
  int price;
};
class Cmp {
public:
  bool operator()(const Node &a, const Node &b) {
    return a.size == b.size ? a.price > b.price : a.size < b.size;
  }
};

int main() {
  std::priority_queue<Node, std::vector<Node>, Cmp> priorityQueue;
  for (int i = 0; i < 5; i++) {
    priorityQueue.push(Node{i, 5 - i});
  }
  priorityQueue.push(Node{4, 0});

  while (!priorityQueue.empty()) {
    Node top = priorityQueue.top();
    std::cout << "size:" << top.size << " price:" << top.price << std::endl;
    priorityQueue.pop();
  }
  return 0;
}
/* 
size:4 price:0
size:4 price:1
size:3 price:2
size:2 price:3
size:1 price:4
size:0 price:5

二进制的读写

向文件写入

int main(int argc, char *argv[]) {
  std::string filename = argv[1];

  std::ofstream file(filename, std::ios::binary | std::ios::out);

  std::bitset<8> num; //(std::string("00000110"));
  num = 0b00000111;
  file << num << std::endl;
  file.close();

  return 0;
}

/* 
执行 ./a.out z.txt

打开 z.txt 可以看到文件内有 00000111

从文件读取

int main(int argc, char *argv[]) {
  std::string filename = argv[1];

  std::ifstream ifile(filename, std::ios::binary | std::ios::in);
  std::string line;
  std::getline(ifile, line);
  std::cout << "line: " << line << std::endl;

  std::bitset<8> bits(line);
  std::cout << bits.to_ulong() << std::endl;

  return 0;
}

/*
执行./a.out z.txt
打印
line: 00000111
7

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
深度学习tricks是指在深度学习模型训练过程中使用的一些技巧和策略,旨在提高模型的性能和训练效果。以下是一些常用的深度学习tricks: 1. 数据增强(Data Augmentation):通过对原始数据进行随机变换和扩充,生成更多的训练样本,以增加模型的泛化能力。 2. 批归一化(Batch Normalization):在每个小批量数据上进行归一化操作,有助于加速模型的收敛速度,提高模型的稳定性和泛化能力。 3. 学习率调整(Learning Rate Schedule):根据训练的进程动态地调整学习率,例如使用学习率衰减或者学习率预热等策略,以提高模型的收敛性能。 4. 正则化(Regularization):通过添加正则化项,如L1正则化或L2正则化,限制模型的复杂度,防止过拟合。 5. 提前停止(Early Stopping):在训练过程中监控验证集上的性能指标,当性能不再提升时停止训练,以避免过拟合。 6. 参数初始化(Parameter Initialization):合适的参数初始化可以帮助模型更快地收敛和更好地泛化,常用的初始化方法包括Xavier初始化和He初始化等。 7. 梯度裁剪(Gradient Clipping):限制梯度的范围,防止梯度爆炸或梯度消失问题,提高模型的稳定性。 8. 集成学习(Ensemble Learning):通过结合多个模型的预测结果,可以提高模型的泛化能力和鲁棒性。 9. 迁移学习(Transfer Learning):利用已经训练好的模型在新任务上进行微调,可以加快模型的训练速度和提高模型的性能。 10. 深度网络结构设计:合理设计网络结构,包括层数、宽度、卷积核大小等,可以提高模型的表达能力和学习能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值