排序&&匿名函数
将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.h
和A.cpp
合并成一个文件
http://www.cnblogs.com/zmkeil/p/5474455.html
好像还可以直接在A.cpp
最后加上template class A<int>;
一个单例模型
- 利用静态成员的析构自动回收内存。(为什么不用自己的析构呢?因为自己的析构需要一个实例结束生命才会进行调用,但是这个类哪里来的实例)
- 静态成员需要在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;
}