运行代码:
//向量vector模板输出、倒置、求和
#include"std_lib_facilities.h"
//定义vector<double>的输入操作符>>
istream& operator>>(istream& is, vector<double>& vv)
{
double dd=0.0;
if(is >> dd)vv.push_back(dd);
return is;
}
//--------------------------------------------------------
//定义向量vector输出操作符<<模板
template<class T>
ostream& operator<<(ostream& os, const vector<T>& vv)
{
for (int i = 0; i < vv.size(); i++)
os << vv[i] << " ";
return os;
}
//---------------------------------------------------------
//定义浮点数向量向整型向量的转换函数
void vd_to_vi(vector<double>vd, vector<int>& vi)
{
for (int i = 0; i < vd.size(); i++)
vi[i] = vd[i];
}
//----------------------------------------------------------
//定义倒转浮点数向量函数
void vd_reserve(vector<double>& vd)
{
vector<double> vd_copy(vd.size());
vd_copy = vd;
for (int i = 0; i < vd.size(); i++)
vd[i] = vd_copy[vd.size() - 1 - i];
}
//-----------------------------------------------------------
//定义计算浮点数向量元素平均值的函数
double vd_medium(vector<double> vd)
{
double sum = 0.0;
sum = accumulate(vd.begin(), vd.end(), sum);
double ve_med = 0.0;
ve_med = sum / vd.size();
return ve_med;
}
//------------------------------------------------------------
int main()
try
{
string read_file="vd_file.txt";
ifstream ifs(read_file.c_str());
if (!ifs)error("can't open ", read_file);
vector<double>vd;
while(ifs >> vd);//读取文件
vd_reserve(vd);//倒置浮点型向量
sort(vd);//对浮点型向量进行升序排序
cout << vd<<"\n\n";
double vd_med = 0.0;
vd_med=vd_medium(vd);//计算浮点型向量平均值
cout << vd_med<<"\n\n";
vector<double>vd2;
for (int i = 0; i < vd.size(); i++)
if (vd[i] < vd_med)vd2.push_back(vd[i]);//将vd中所有取值小于平均值的元素拷贝至vd2中
cout << vd2 << "\n\n";
vector<int>vi(vd.size());
vd_to_vi(vd, vi);//浮点数向量向整型向量的转换
cout << vi << "\n\n";
for (int i = 0; i < vd.size(); i++)
cout << "( " << vd[i] << " , " << vi[i] << " )" << "\n";//按(vd[i],vi[i])格式输出
double vd_sum = 0.0;
vd_sum = accumulate(vd.begin(), vd.end(), vd_sum);//计算浮点数向量元素总和
cout << "\n"<<vd_sum<<"\n\n";
int vi_sum = 0;
vi_sum = accumulate(vi.begin(), vi.end(), vi_sum);//计算整型向量元素总和
cout << vi_sum << "\n\n";
double di_difference = 0.0;
di_difference = vd_sum - vi_sum;//计算浮点数向量元素总和与整型向量元素总和的差值
cout << di_difference << "\n\n";
return 0;
}
catch (exception& e) {
cerr << "error:" << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops:unknown exception!\n";
keep_window_open();
return 2;
}
读取文件:vd_file.txt
34.3
543.32
44.3
34.5
234.5
34.55
434.5
56.7
5656.7
45.2
56.4
4.5
0.4
54.2
54.0
45.34
4.34
545.34
运行结果: