c++的一些记不住的特性= =

排序&&匿名函数

将map按value排序

#include <utility> // for pair
#include <algorithm> // for sort
typedef pair<string, long long> t_pair;  
std::vector<t_pair> v;
for (std::map<std::string, long long>::iterator it=m_accTime.begin(); it!=m_accTime.end(); ++it)
    v.push_back(make_pair(it->first, it->second));
std::sort(v.begin(), v.end(), [](const t_pair& d1, const t_pair& d2){
        return d1.second > d2.second;
});

模板类

一般写法

// a.h
#ifndef A_H_
#define A_H_
template <typename Dtype>
class A{
public:
    A(){};
    void Swap(Dtype& a, Dtype& b);
};
#endif 

// a.cpp
#include "./A.h"
template <typename Dtype>
void Swap(Dtype& a, Dtype& b){
    Dtype tmp=a;
    a=b; b=tmp;
}
//main.cpp
#include "A.h"

int main(){
    A<int> a;
    int x=3, y=4;
    a.Swap(x, y);
}

这样编译main.cpp是会报undefined referenced错的。
对‘A<int>::Swap(int&, int&)’未定义的引用
原因是在这里,Swap只有一个模板的声明,也就是Swap(Dtype, Dtype)。
初想可以通过在A.cpp里面加入template<> void Swap(int &a, int &b)
来进行模板实例化,但是好像也没有用。
网上的解决方式是。将A.hA.cpp合并成一个文件
http://www.cnblogs.com/zmkeil/p/5474455.html
好像还可以直接在A.cpp最后加上template class A<int>;

一个单例模型

  1. 利用静态成员的析构自动回收内存。(为什么不用自己的析构呢?因为自己的析构需要一个实例结束生命才会进行调用,但是这个类哪里来的实例)
  2. 静态成员需要在cpp进行定义
//timer.hpp
#ifndef TIMER_H
#define TIMER_H
#include <sys/time.h>
#include <iostream>
#include <string>

    class Timer{
    private:
        Timer(){}
        static Timer* m_timer;
        struct timeval m_startTime;
        class Garbo{
        public:
            ~Garbo(){
                if(Timer::m_timer)
                    delete m_timer;
            }
        };
        static Garbo m_garbo; // will delete m_timer when program finished
    public:
        static Timer * GetInstance();
        void Start();
        long int GetTimeInterval();
        void PrintTimeInterval(std::string );
    };


#endif
// timer.cpp
    Timer* Timer::m_timer;//static成员必须在cpp进行定义
    Timer * Timer::GetInstance(){
        if(m_timer == NULL)
            m_timer = new Timer();
        return m_timer;
    }
    void Timer::Start(){
        gettimeofday(&m_startTime, NULL);
    }
    long int Timer::GetTimeInterval(){
        struct timeval endTime; 
        gettimeofday(&endTime, NULL);   
        long int timeInterval = (endTime.tv_sec-m_startTime.tv_sec)*1000000 +  endTime.tv_usec-m_startTime.tv_usec;
        return timeInterval;
    }
    void  Timer::PrintTimeInterval(std::string str=""){
        //printf(str+" Time: %ld\n", GetTimeInterval() );
        std::cout<<str<<" Time: "<<GetTimeInterval()<<std::endl;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值