排序功能中的'operator='不匹配

No match for 'operator=' in sort function

本文关键字:不匹配 operator 功能 排序      更新时间:2023-10-16

我试图让程序写出字符串的所有排列。这是我的代码:

#include <stdio.h>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main () {
    string input;
    int length;
    cin >> input;
    input = sort(begin(input), end(input));
    length = input.length();
    do {
        cout << input;
        cout << "n";
    } while (next_permutation(input,input+length));
}

但是,我收到以下错误:

[path removed]PermutIO.cpp|12|error: no match for 'operator=' in 'input = std::sort<__gnu_cxx::__normal_iterator<char*, std::basic_string<char> > >(std::begin<std::basic_string<char> >((* & input)), std::end<std::basic_string<char> >((* & input)))'|

我正在使用带有 g++ 的代码::块,并将其设置为使用 C++11 标准。似乎有什么问题?

sort方法本身返回一个void,所以你要做的是将string分配给void。只需写sort(begin(input), end(input))

更新:
好吧,让我们分析一下编译器给出的错误消息:

error: no match for 'operator=' in 'input = 
std::sort<__gnu_cxx::__normal_iterator<char*, std::basic_string<char> > >
(std::begin<std::basic_string<char> >((* & input)), 
std::end<std::basic_string<char> >((* & input)))'

最后 3 行可能看起来很难理解,但这里最重要的是第一行:

no match for 'operator=' in 'input = ...

这意味着编译器找不到规则,该规则可以让您将input分配给右侧的某些内容。所以,现在,当我们已经知道问题出在赋值上时,调试过程要简单得多 - 我们必须找到sort方法返回什么类型的值,我们可以简单地通过使用 google 来做到这一点。

此行格式不正确,因为std::sort返回void

input = sort(begin(input), end(input));

不能将void分配给std::string

从该行中删除input =。 不需要。