You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++代码调用for_each出现error C2672错误,请求排查问题原因

问题分析与解决:for_each匹配错误

错误原因

代码中wc是通过find_if(words.cbegin(), words.cend(), bind(check_size, _1, sz))获取的迭代器,cbegin()和cend()返回的是常量迭代器(const_iterator),指向的元素不可修改。但后续for_each使用的lambda表达式参数是string& s(非常量引用),试图绑定到常量迭代器指向的const string对象上,类型不兼容,导致编译器找不到匹配的for_each重载函数。

修正方案

有两种合理的修正方式,按需选择:

  • 方案一(推荐):由于lambda仅用于打印元素,无需修改内容,将lambda参数改为const string& s,适配常量迭代器:
    for_each(wc, words.end(), [](const string& s)-> void {cout << s << endl; });
    
  • 方案二:如果后续需要修改元素,将find_if中的cbegin()/cend()替换为begin()/end(),让wc成为普通迭代器:
    auto wc = find_if(words.begin(), words.end(), bind(check_size, _1, sz));
    

修正后的完整代码

#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <functional>

using namespace std;
using namespace std::placeholders;

void elimDups(vector<string>& words)
{
    sort(words.begin(), words.end());
    auto end_unique = unique(words.begin(), words.end());
    words.erase(end_unique, words.end());
}

string make_plural(string::size_type count, string str, string plur)
{
    return count > 1 ? str + plur : str;
}

bool check_size(const string& s, vector<string>::size_type sz)
{
    return s.size() > sz;
}

void biggies(vector<string>& words, vector<string>::size_type sz)
{
    elimDups(words);
    stable_sort(words.begin(), words.end(),
        [](const string& a, const string& b) -> bool { return a.size() < b.size(); });

    auto wc = find_if(words.cbegin(), words.cend(), bind(check_size, _1, sz));
    auto count = words.end() - wc;
    cout << count << " " << make_plural(count, "word", "s") << " of length " << sz << " or longer" << endl;
    // 修改lambda参数为const引用
    for_each(wc, words.end(), [](const string& s)-> void {cout << s << endl; });
}

int main()
{
    istringstream os("the quick red fox jumps over the slow red turtle");
    string word;
    vector<string> svec;
    while (os >> word)
        svec.push_back(word);
    biggies(svec, 5);
    return 0;
}

内容的提问来源于stack exchange,提问作者gaofeng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 02:00:40