zoukankan      html  css  js  c++  java
  • [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;  
    }


  • 相关阅读:
    Inno Setup执行SQL脚本的方法
    批处理命令篇--配置免安装mysql
    nsis安装包_示例脚本语法解析
    全方位掌握nsis脚本
    dos批处理知识
    mysql alter 语句用法,添加、修改、删除字段等
    .Net WebAPI 增加Swagger
    CentOS 7 Docker
    四:Ionic Framework不支持Android4.2.2的解决方法
    二:Ionic Framework支持Android开发
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787097.html
Copyright © 2011-2022 走看看