2016-04-15 43 views
0

我的代码接受一个字符串,并试图检查是否存在一个输入字符串的排列或不存在。如果存在一个这样的字符串,打印它否则打印“没有答案”。但我的代码doesn' t编译并显示错误。 错误是::没有匹配函数调用'next_permutation(std :: string &)'| 完成此任务的正确方法是什么?next_permutation in C++ on strings

#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 
    } 
} 
+2

你读过错误消息了吗?我建议您在发布到stackoverflow之前作为您的第一步。 – user2079303

+0

@ user2079303调用'next_permutation(std :: string&)'时没有匹配函数| –

+0

将相关信息也放入问题中,而不只是在评论中。 – user2079303

回答

0

下面是功能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; 
} 

这是尽管你可能不得不改变逻辑来完成任务

+0

那么这样做的正确方法是什么? –

+0

@satya查看更新后的代码 –

0

编译错误是很清楚的:

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

编译器告诉你,不存在功能next_permutation(std::string&)。如果你看看documentation,你会发现的确如此。有两种过载:

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将迭代器获取到字符串内的字符范围。

0

这是要做到这一点

 // 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; 

      } 
     } 
+0

@RajeevSingh yes –

0

此代码也是正确的方法解决了这个问题:

#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 
    } 
}