Reputation: 163
My code accepts a string and tries to check if there exists a permutation of the input string or not.If there exists one such string ,print it else print "no answer ".But my code doesn't compile and shows error. error is ::no matching function for call to 'next_permutation(std::string&)'| what is the correct method to accomplish this task ?
#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
}
}
Upvotes: 1
Views: 8345
Reputation: 13651
This code also solves the problem:
#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
}
}
Upvotes: 0
Reputation: 163
this is the correct way to do this
// 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;
}
}
Upvotes: 0
Reputation: 3332
Here are the prototypes of the function next_permutation
and your calling statement string ans=next_permutation(s);
doesn't matches any of them.
template <class BidirectionalIterator>
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last);
template <class BidirectionalIterator, class Compare>
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last, Compare comp);
Change your code like this to check weather a permutation exits or not
if(next_permutation(s.begin(),s.end()))
cout<<s<<endl;
else
cout<<"no answer "<<endl;
And If you want to print all the permutations of s
then do this
while(next_permutation(s.begin(),s.end()))
{
cout<<s<<endl;
}
This is the way to do it,although you may have to change the logic to accomplish the task
Upvotes: 2
Reputation: 238311
The compilation error is quite clear:
no matching function for call to 'next_permutation(std::string&)'|
The compiler tells you that there exists no function next_permutation(std::string&)
. If you take a look at the documentation, you'll find that is indeed the case. There are two overloads:
template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );
template< class BidirIt, class Compare >
bool next_permutation( BidirIt first, BidirIt last, Compare comp );
Neither of them matches your call.
Use std::string::begin
and std::string::end
to get iterators to the range of characters inside the string.
Upvotes: 0