C++位运算,全排序,全组合

C++ STL 全排列函数详解

STL方法:

#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
    int arr[] = {3,2,1};
    cout<<"用prev_permutation对3 2 1的全排列"<<endl;
    do
    {
        cout << arr[0] << ' ' << arr[1] << ' ' << arr[2]<<'\n';
    }
    while ( prev_permutation(arr,arr+3) );      ///获取上一个较大字典序排列,如果3改为2,只对前两个数全排列

    int arr1[] = {1,2,3};
    cout<<"用next_permutation对1 2 3的全排列"<<endl;
    do
    {
        cout << arr1[0] << ' ' << arr1[1] << ' ' << arr1[2] <<'\n';
    }
    while ( next_permutation(arr1,arr1+3) );      ///获取下一个较大字典序排列,如果3改为2,只对前两个数全排列
    ///注意数组顺序,必要时要对数组先进行排序

    return 0;
}

全排列算法

调试代码。至于讲解没时间写了,看看原博客的吧。

#include <iostream>

using namespace std;
template <typename T>
inline void swap(T* array, unsigned int i, unsigned int j)
{
    T t = array[i];
    array[i] = array[j];
    array[j] = t;
}

/*
 * 递归输出序列的全排列
 */
void FullArray(char* array, size_t array_size, unsigned int index)
{
    if(index >= array_size)
    {
        for(unsigned int i = 0; i < array_size; ++i)
        {
            cout << array[i] << ' ';
        }
        cout << '\n';
        return;
    }
    for(unsigned int i = index; i < array_size; ++i)
    {
        swap(array, i, index);
        FullArray(array, array_size, index + 1);
        swap(array, i, index);
    }
}

int main()
{
	char array[5]={'a','b','c','d','e'};
	FullArray(array,5,0);
	return 0;
}

全排列和全组合实现

全组合:

这些结果的位图值都是 1,2…2^n-1。所以从值 1 到值  依次输出结果:

001,010,011,100,101,110,111 。对应输出组合结果为:a,b,ab,c,ac,bc,abc

#include<stdio.h>
#include<string.h>
void Combination(char *str)
{
	if(str == NULL)
		return ;
	int len = strlen(str);
	int n = 1<<len;
	for(int i=1;i<n;i++)    //从 1 循环到 2^len -1
	{
		for(int j=0;j<len;j++)
		{
			int temp = i;
			if(temp & (1<<j))   //对应位上为1,则输出对应的字符
			{
				printf("%c",*(str+j));
			}
		}
		printf("\n");
	}
}
void main()
{
	char str[] = "abc";
	Combination(str);
}

 

C++ bitset 常用函数及运算符

#include <iostream>  
#include <bitset>  
using namespace std;  
  
int main() {  
    unsigned short short1 = 4;      
    bitset<16> bitset1{short1};   // the bitset representation of 4  
    cout << bitset1 << endl;  // 0000000000000100  
  
    unsigned short short2 = short1 << 1;     // 4 left-shifted by 1 = 8  
    bitset<16> bitset2{short2};  
    cout << bitset2 << endl;  // 0000000000001000  
  
    unsigned short short3 = short1 << 2;     // 4 left-shifted by 2 = 16  
    bitset<16> bitset3{short3};  
    cout << bitset3 << endl;  // 0000000000010000  
}  
  

glibc的几个有用的处理二进制位的内置函数

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值