[C++] next_permutation的函数 与 copy() 函数的用法

全排列算法,然后发现C++的STL有一个函数可以方便地生成全排列,这就是next_permutation

在C++ Reference中查看了一下next_permutation的函数声明:

#include <algorithm>
bool next_permutation( iterator start, iterator end );

The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.

从说明中可以看到 next_permutation 的返回值是布尔类型。按照提示写了一个标准C++程序:

#include <iostream>
#include <algorithm>
#include <string>
 
using namespace std;
 
int main()
{
    string str;
    cin >> str;
    sort(str.begin(), str.end());
    cout << str << endl;
    while (next_permutation(str.begin(), str.end()))
    {
        cout << str << endl;
    }
    return 0;
}

其中还用到了 sort 函数和 string.begin()、string.end() ,函数声明如下:

#include <algorithm>
void sort( iterator start, iterator end );

sort函数可以使用NlogN的复杂度对参数范围内的数据进行排序。

路人 : 你一定没开 g++ -O2 优化…… 开了 O2 之后 STL 的大部分迭代器和指针等同。

c++STL中copy函数的用法解读

#include <algorithm>  
#include <vector>  
using namespace std;  
  
int main ()   
{  
  int myints[]={10,20,30,40,50,60,70};  
  vector<int> myvector;  
  
  myvector.resize(7);     
  
  //将数值复制到vector里,参数依次是开始、结束,vector数组的开始  
  copy (myints, myints+7, myvector.begin() );  
  
  cout << "myvector contains:\n";  
  //将数值复制到输出流中,参数依次是开始、结束,输出流  
  copy(myvector.begin(), myvector.end(), ostream_iterator<int>(cout, " "));  
  
  cout << endl;  
  
  return 0;  
}


posted @ 2013-02-02 10:29  小尼人00  阅读(169)  评论(0编辑  收藏  举报