1. 程式人生 > >學習C++中的有用函式

學習C++中的有用函式

1:
int __builtin_popcount(int x)
long long __builtin_popcountll(long long x)
求數字x二進位制中的1的個數
實測:

#include<cstdio>

int main()
{
	long long x = 1ll<<60;
	printf("%d\n",__builtin_popcount(x));
	printf("%d\n",__builtin_popcountll(x));
	/*
		output:
		0
		1
	*/
}

2:
sort(a+l,a+r(,cmp))
stable_sort(a+l,a+r(,cmp))
nth_element(a+l,a+k,a+r(,cmp))
(,cmp) 表示比較函式,可加可不加。
sort是比較常用的排序,表示將a+l到a+r-1的元素排序。O(nlogn)
stable_sort是sort的穩定排序版本,和sort在用法和時間複雜度上一致。
stable_sort在排序時如果兩個資料在比較函式的定義下相等,則不會交換,相當於把每個元素ai定義為pair<XXX,i>=(ai , i)然後sort。。。
nth_element是使用快速選擇演算法,求出第k大的STL函式。
表示在a+l到a+r-1中第k大的將會被放到a+k的位置上,比他小的都在a+k前,比他大的都在a+k後。