使用cout进行格式化、lambda表达式

本文详细介绍了如何在C++中使用cout进行高级格式化输出,包括精度控制、对齐方式等,并探讨了lambda表达式的使用技巧,如何创建、捕获变量以及在函数式编程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
int main()
{
 int a = 21;
 cout << std::hex << a << endl;
 cout.width(5);   // 只作用于下一个项目
 cout.fill('*'); // 一直有效,直到被重新设置
 cout << std::oct << a << endl;
 cout <<std::setfill(' ')<<std::setw(1)<< std::dec << a << endl;// C/C++的原则是:显示所有的数据比保持列的整洁更重要
 cout.precision(2);//一直有效,直到被重新设置
 cout << 15.6 << endl;
 cout <<std::setprecision(6)<< std::fixed <<15.6<< endl;
 cout << std::scientific << 15.6 << endl;
 cout.unsetf(std::ios_base::floatfield);
 cout << 15.60 << endl << std::showpoint << 15.60 << endl;
 // 其他一些istream方法:
 // get()、getline()、ignore()、read()(前四种方法是非格式化抽取方法)、peek()、gcount()、putback()等。
 // 其他一些ostream方法:put()、write(),前者用于显示字符,后者用于显示字符串。
 // flush和endl刷新缓冲区,后者插入一个换行符。
 return 0;
}

在这里插入图片描述

在#include <iostream>
#include <iomanip>
#include <vector>
#include <ctime>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
class f_mod  //fmod是个系统函数
{
private: 
 int mod;
public:
 f_mod() { mod = 5; }
 f_mod(const int& m) :mod(m) {}
 bool operator()(const int& n) { return n % mod == 0; }
}f;
bool f3(const int& x) { return x % 3 == 0; }
int main()
{
 std::vector<int>numbers(10);
 std::srand(std::time(0));
 std::generate(numbers.begin(), numbers.end(), std::rand);
 for (auto p = numbers.begin(); p != numbers.end(); p++)
  cout << *p << endl;

 // 函数指针
 int count3 = std::count_if(numbers.begin(), numbers.end(), f3);
 
 // 函数符
 int count5 = std::count_if(numbers.begin(), numbers.end(), f_mod(5));
 
 // lambda表达式
 int count7 = std::count_if(numbers.begin(), numbers.end(), [](const int&x) { return x % 7 == 0; });
 
 auto mod7 = [](const int& x) {return x % 7 == 0; };
 int count7_ = std::count_if(numbers.begin(), numbers.end(), mod7);
bool result = mod7(15);

 int count9 = 0;
 std::for_each(numbers.begin(), numbers.end(), [&count9](const int& x) {count9 += x % 9 == 0; });
 
 int count11 = 0, count13 = 0, count15 = 0;
 std::for_each(numbers.begin(), numbers.end(), [&](const int& x) {count11 += x % 11 == 0; count13 += x % 13 == 0; count15 += x % 15 == 0; });
 
 cout << count3 << endl << count5 << endl << count7 << endl 
  << count7_<< endl << count9 << endl << count11 << endl 
  << count13 << endl << count15<<endl;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值