C++ 去除重复项且获取到不重复部分
2021/12/15 17:17:25
本文主要是介绍C++ 去除重复项且获取到不重复部分,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目的
假设有这一个需求。
去重复并获取独立部分
例如下面两个
1.字符串"1233214" -> "4"
2.字符串数组{ "1","2","3","3","2","1","4" } -> { "4" }
很直白,不多说。
上代码
完整代码
#include <iostream> #include <string> #include <vector> #include <list> #include <map> // 去重复获取独立部分 // 1.字符串"1233214" -> "4" // 2.字符串数组{ "1","2","3","3","2","1","4" } -> { "4" } template <typename MajorType, typename MinorType> MajorType removeRepeat(MajorType& src) { MajorType result_vec = MajorType(); if (src.empty()) return result_vec; const int _ONE = 1; std::map<MinorType, int> tmp_map; for (auto itor = src.begin(); itor != src.end(); ++itor) { ++tmp_map[*itor]; } for (auto itor = tmp_map.begin(); itor != tmp_map.end(); ++itor) { if ((*itor).second == _ONE){ result_vec.push_back((*itor).first); } } return result_vec; } int main(int argc, char **argv) { std::cout << "将要去重的字符串数组原型[1,2,3,3,2,1,4] or 字符串原型1233214" << std::endl; // vector容器类去重 std::vector<std::string> test_vec; test_vec.push_back("1"); test_vec.push_back("2"); test_vec.push_back("3"); test_vec.push_back("3"); test_vec.push_back("2"); test_vec.push_back("1"); test_vec.push_back("4"); std::vector<std::string> resut_vec = removeRepeat<std::vector<std::string>, std::string>(test_vec); std::cout << "【vector】 \t去除结果:"; for (auto item : resut_vec) { std::cout << item << " "; } std::cout << std::endl; // list容器类去重 std::list<std::string> test_list; test_list.push_back("1"); test_list.push_back("2"); test_list.push_back("3"); test_list.push_back("3"); test_list.push_back("2"); test_list.push_back("1"); test_list.push_back("4"); std::list<std::string> resut_list = removeRepeat<std::list<std::string>, std::string>(test_list); std::cout << "【list】 \t去除结果:"; for (auto item : resut_list) { std::cout << item << " "; } std::cout << std::endl; // string 类型去重 std::string test_string; test_string += std::string("1"); test_string += std::string("2"); test_string += std::string("3"); test_string += std::string("3"); test_string += std::string("2"); test_string += std::string("1"); test_string += std::string("4"); std::string resut_string = removeRepeat<std::string, char>(test_string); std::cout << "【string】 \t去除结果:" << resut_string; std::cout << std::endl; return 0; }
调试结果:
_End
完事儿。
这篇关于C++ 去除重复项且获取到不重复部分的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享