1、const成员函数以及返回引用
#include <stdio.h>
#include <string>
#include <iostream>
class leslieyuan {
public:
leslieyuan(std::string name, int age) : m_name(name),m_age(age) {}
~leslieyuan() {}
public:
std::string& getName() const { return const_cast<std::string&>(m_name); } //将成员变量的const属性去除后作为一个引用类型返回,就可以在外部修改成员变量
int& getAge() const { return const_cast<int&>(m_age); }
private:
std::string m_name;
int m_age;
};
int main(int argc,char* argv[])
{
leslieyuan yuan("leslieyuan",26);
std::string& name = yuan.getName();
int& age = yuan.getAge();
age = 18;
name[0] = 'L';
std::cout << yuan.getName()<< std::endl;
std::cout << yuan.getAge() << std::endl;
}
2、c++浮点数比较和排序——踩坑
float a = 1;
float b = 2;
if (fabs(a - b) > FLT_EPSILON )
{
//do sth
}
#include <iostream>
#include<algorithm>
#include<cmath>
#define EPSILON 1e-6
using namespace std;
int n;
double num[105];
bool cmp(double a, double b) {
//判断a、b到向上取整的数和向下取整的数的差,取最小的
double x_a = a - (int)a; //到向下取整的那个数的差
double xx_a = abs(a - (int)a - 1); //到向上取整的差
double s_a = min(x_a, xx_a);
double x_b = b - (int)b;
double xx_b = abs(b - (int)b - 1);
double s_b = min(x_b, xx_b);
if(fabs(s_a - s_b) < EPSILON){//差相等,按浮点数从小到大
return a < b;
}
return s_a < s_b;
}
int main() {
cin>>n;
for(int i = 0; i <= n; i++){
cin>>num[i];
}
sort(num, num + n, cmp);
for(int i = 0; i < n; i++){
if(i < n - 1)
printf("%.6lf ", num[i]);
else
printf("%.6lf\n", num[i]);
}
return 0;
}