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

完事儿。

posted @ 2021-12-15 16:52  想想就很离谱  阅读(289)  评论(0编辑  收藏  举报