字符串上的c++中的next置换

next_permutation in c++ on strings

本文关键字:next 置换 中的 c++ 字符串      更新时间:2023-10-16

我的代码接受一个字符串,并尝试检查输入字符串是否存在排列。如果存在这样的字符串,打印它,否则打印"no answer"。但我的代码没有编译,并显示错误。错误为::没有匹配的函数用于调用"next_premotion(std::string&)"|完成这项任务的正确方法是什么?

#include <bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        string s;
        cin>>s;
        string ans=next_permutation(s);// do permutation and store it in string ans
        if(ans==s)// if there is no permutation possible original and ans will be same
            cout<<"no answer "<<endl;
        else
            cout<<ans<<endl;// else print ans
    }
}

以下是函数next_permutation的原型,而您的调用语句string ans=next_permutation(s);与其中任何一个都不匹配。

template <class BidirectionalIterator>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last);
template <class BidirectionalIterator, class Compare>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last, Compare comp);

像这样更改代码以检查排列是否存在

if(next_permutation(s.begin(),s.end()))
    cout<<s<<endl;
else
    cout<<"no answer "<<endl;

如果你想打印s的所有排列,那么就做这个

while(next_permutation(s.begin(),s.end()))
{
    cout<<s<<endl;
}

这就是实现它的方法,尽管您可能需要更改逻辑来完成任务

编译错误非常明显:

no matching function for call to 'next_permutation(std::string&)'| 

编译器告诉您不存在函数next_permutation(std::string&)。如果你看一下文档,你会发现事实确实如此。有两个过载:

template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );
template< class BidirIt, class Compare >
bool next_permutation( BidirIt first, BidirIt last, Compare comp );

它们都不符合你的要求。

使用std::string::beginstd::string::end可以将迭代器设置为字符串内的字符范围。

这是完成的正确方法

       // thanks to rajeev's code
       #include <bits/stdc++.h>
         using namespace std;
         int main(){
         int t;
         cin>>t;
         while(t--){
           string s;
           cin>>s;
           bool ans=next_permutation(s.begin(),s.end());
           if(!ans)
           cout<<"no answer "<<endl;
           else
           cout<<s<<endl;
            }
         }

此代码还解决了问题:

#include <bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        string s;
        cin>>s;
        string original_s=s; // store the input string in a variable as original_s
        next_permutation(s.begin(),s.end());// do permutation and s will be changed if permutation occurs
        if(s==original_s)// if there is no permutation possible original and s will be same
            cout<<"no answer "<<endl;
        else
            cout<<s<<endl;// else print ans
    }
}