迭代器的使用实例

本文介绍了一个使用C++编写的简单程序,该程序能够读取一行输入的文本,并统计其中字母、数字及空格的数量。通过使用标准库中的函数如isalpha(), isdigit() 和 isspace()来识别字符类型,最后将这些数量存储在一个vector容器中,并按降序排序输出。

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

//统计字符
#include <vector>
#include<iostream>
#include<string>
#include<cctype>
#include <algorithm>
using namespace std;

int main()
{
	string str;
	vector<int> v;
	vector<int>::iterator iter = v.begin();
	getline(cin, str);
	int len = str.size(), letter_n = 0, digit_n = 0, space_n = 0;
	for (int i = 0; i<len; i++)
	{
		if (isalpha(str[i]))
			letter_n++;
		else if (isdigit(str[i]))
			digit_n++;
		else if (isspace(str[i]))
			space_n++;
	}
	v.push_back(letter_n);
	v.push_back(digit_n);
	v.push_back(space_n);
	/* for (iter = v.begin(); iter != v.end(); iter++)
	cout << *iter<<',';
	cout << endl; */ //普通迭代器输出
	sort(v.rbegin(), v.rend(), less<int>());
	cout << "反向迭代器输出: " << endl;
	vector<int>::reverse_iterator it = v.rbegin();
	while (it != v.rend())
	{
		cout << *it << " ";
		++it;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值