【问题标题】:Could not find a match for 'std::transform..."找不到“std::transform...”的匹配项
【发布时间】:2013-06-30 18:17:57
【问题描述】:

我有这个奇怪的错误,代码之前可以工作,但过了一段时间它停止编译。 错误是:

Could not find a match for 'std::transform<InputIterator,OutputIterator,UnaryOperation>(char *,char *,char *,charT (*)(charT,const locale &))' in function main() 

它所指的行是:

    string ans;
    cin>>ans;
    std::transform(ans.begin(), ans.end(), ans.begin(), ::tolower);

有人可以帮我解释一下为什么会这样吗? 我使用的包括:

#include <fstream.h>;
#include <iostream.h>;
#include <string>;
#include <time.h>;
#include <vector>;
using namespace std;

非常感谢

【问题讨论】:

  • @Samoth 使用指针作为迭代器有什么问题?
  • 问题出在::tolower,而不是迭代器。您不能直接传递该函数,因为它需要两个参数。见这里:stackoverflow.com/a/314163/777186
  • 啊哈,找到了:en.cppreference.com/w/cpp/locale/tolower 最近有人在你的代码中添加了#include &lt;locale&gt; 吗?
  • 您应该发布一个完整的(但最少的)示例,显示您使用的包含以及任何 using 指令和/或声明。
  • &lt;fstream.h&gt; 等都是非标准的。使用&lt;fstream&gt;&lt;iostream&gt;&lt;ctime&gt;

标签: c++ templates runtime transform lowercase


【解决方案1】:

如果您所说的这种情况直到最近才起作用,我必须假设有人在代码的其他地方引入了一个小改动,这会破坏事情。 现在,这行得通:

#include <string>
#include <algorithm>
#include <cctype>
#include <iterator>
#include <iostream>

int main()
{
    std::string s1 {"Hello"}, s2;
    std::transform(
            std::begin(s1),
            std::end(s1),
            std::back_inserter(s2),
            ::tolower);
    std::cout << s2 << '\n';
}

即它打印hello。 如果我在顶部添加这两行:

#include <locale>
using std::tolower;

我收到与您类似的错误(不完全相同)。这是因为它将this version of tolower 带入范围。 要取回“正确”版本(假设您确实指的是 cctype 标头中的版本?)您可以使用 static_cast 来选择您想要的版本:

// ...

#include <locale>
using std::tolower;

int main()
{
    std::string s1 {"Hello"}, s2;
    std::transform(
            std::begin(s1),
            std::end(s1),
            std::back_inserter(s2),
            static_cast<int(*)(int)>(::tolower)); // Cast picks the correct fn.
    std::cout << s2 << '\n';
}

编辑:我不得不说,我很困惑为什么你要专门选择那个版本,而不是得到一个模棱两可的错误。但我无法准确猜测您的代码中发生了什么变化......

【讨论】:

    【解决方案2】:

    它对我有用。也许你忘了包含&lt;algorithm&gt;

    它应该这样工作:

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
       string ans;
        cin>>ans;
        std::transform(ans.begin(), ans.end(), ans.begin(), ::tolower);
       cout << ans;
       return 0;
    }
    

    【讨论】:

    • 他确实应该#include &lt;algorithm&gt; 但错误消息表明编译器确实知道transform 的签名,所以它正在以某种方式被拾取(在其他一些include 我想)。
    • 我试过了,它对我有用。也许在您的编译器中,您必须为 tolower 添加其他内容?
    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多