字符串上的c++中的next置换
next_permutation in c++ on strings
我的代码接受一个字符串,并尝试检查输入字符串是否存在排列。如果存在这样的字符串,打印它,否则打印"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::begin
和std::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
}
}
相关文章:
- 对于set上的循环-获取next元素迭代器
- 为什么 std::next 在以空地图开头馈送时卡住
- 为什么gmp会在这里与"invalid next size"重新定位一起崩溃?
- "fast"或"normal"在"free(): invalid next size (fast)"中是什么意思?
- 犰狳(C++)中的快速阵列置换(广义张量转置)
- curl_slist->next 永远不会为空,因此当循环卡住时
- std::next 是否检查我们是否已经在容器的末尾?
- Clang, std::next, libstdc++ and constexpr-ness
- 错误 C2864:'element::next':只能在类 (STRUCT) 中初始化静态常量整数数据成员
- 检查两个字符串是否彼此置换
- 查找随机置换阵列的AVG数量
- 在 c++ 程序中调试链表以添加两个数字: 有人可以解释为什么 l3=l3->next;导致错误?
- head->next 不为空
- LinkedListInit, LinkedListCreateH 方法中的"L->next=NULL"有什么问题吗?
- 从文件中获取数据时如何放置换行符?
- C++ 带有 hasNext 和 Next 的迭代器
- 是 std::next 对于向量 O(n) 或 O(1)
- 如何检查STD :: Next(x)指向C 中的有效地址
- 跟进哈希表 C++,this->next = NULL 指针
- 字符串上的c++中的next置换