1. 程式人生 > >關於幾個統計用的C++方法

關於幾個統計用的C++方法

最近要用到關鍵詞的統計。在網上找了一些方法,所以總結一下,供參考。

利用map的特性進行同關鍵詞的數量統計,模糊匹配的話可以把資訊抽象成一個類,然後過載 < 操作符進行型別資訊的區分.


	//統計相同組的同學數量
	struct Student
	{
		int id;
		std::string name;
		int group; //組
		std::string groupName; //組名
	};
	struct CompareVV_t
	{
		bool operator()(Student l, Student r)
		{
			return l.group < r.group;
		}
	};

	std::map<Student, int, CompareVV_t> statisticsVV;
	statisticsVV[Student]++;

	//統計組容納人數最多的三個組
	typedef std::pair<Student, int> PAIR;
	std::vector<PAIR> vec(statisticsVV.begin(), statisticsVV.end());

	struct CompareNum
	{
		bool operator()(PAIR l, PAIR r)
		{
			return l.second > r.second;
		}
	};
	std::partial_sort(vec.begin(),vec.begin()+2, vec.end());

	//查詢人數第三的組  vec.begin()+2
	std::nth_element(vec.begin(),vec.begin()+2, vec.end());