博客
关于我
重函数unique的使用以及map的扩展
阅读量:362 次
发布时间:2019-03-04

本文共 1083 字,大约阅读时间需要 3 分钟。

一、unique函数的应用

在C++编程中,unique函数主要用于去除数组中相邻重复元素。要实现这一功能,首先需要包含相应的头文件<algorithm>。以下是使用unique函数的一个示例:

#include 
#include
using namespace std;int a[256];int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a, a + n); int unique_count = unique(a, a + n) - a; // unique_count表示去重后的个数 for (int i = 0; i < n; ++i) { // 依次输出所有元素 }}

注意事项:在使用unique函数前,数组需要先进行排序。这样可以确保相邻重复元素被正确识别并去除。


二、map容器的应用

除了使用unique函数统计去重后的元素个数,我们还可以使用map容器来找出数组中最多的重复元素。以下是一个示例:

#include 
#include
using namespace std;int main() { map
mp; int n, a; cin >> n; for (int i = 1; i <= n; ++i) { cin >> a; mp[a]++; } int total_unique = mp.size(); // total_unique表示数组中不同元素的数量 int max_repeated = -9999; // max_repeated表示数组中最多重复的元素的数量 for (auto it = mp.begin(); it != mp.end(); ++it) { if (it->second > max_repeated) { max_repeated = it->second; } } cout << total_unique << endl;}

通过上述代码,我们可以轻松地统计出数组中不同元素的数量以及最多重复的元素的数量。这一方法相比传统的双重循环方法更加高效且简洁。

转载地址:http://lgfg.baihongyu.com/

你可能感兴趣的文章
order by rand()
查看>>
SSM(Spring+SpringMvc+Mybatis)整合开发笔记
查看>>
ViewHolder的改进写法
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
sql查询中 查询字段数据类型 int 与 String 出现问题
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
查看>>