注册 登录
编程论坛 C++教室

关于向算法传递函数的问题

哒哒哒啦啦啦 发布于 2016-06-13 05:09, 3252 次点击
程序是没错的目前,目的是选出比输入的长度“n”长的string,就是有一个之前的报错不太明白。。

#include <iostream>
#include <string>
#include <vector>
#include<stack>
#include<algorithm>
using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::vector;
int main()
{
    std::vector<std::string> v
    {
        "1234","1234","1234","hi~", "alan", "alan", "cp"
    };


    string::size_type n = 4;
    vector<string> b( v.size());
    stable_sort(v.begin(), v.end(), [](string const a, string const b) {return a.size() <b.size(); });


    //**********上面这句是想排序用的,但是按照这行注解的这种写法总是报错:项不会计算为接受2个参数的函数,
    //我知道这种排序的算法肯定不对,但是语法应该没错,不知为何会这么报错呢,还是就是因为算法不对就这么报,不知大神们明白我的意思吗。。   
    //         stable_sort(v.begin(), v.end(), [n](string const a) {return a.size() >= n; });
   
   
   
    for (auto i : v)
        cout << i << " ";
    cout << endl;
    auto ptr = unique(v.begin(), v.end());
    v.erase(ptr, v.end());
 
    auto p = find_if(v.begin(), v.end(), [n](string const a) {return a.size() >=n; });
    copy(p, v.end(), b.begin());

    for (auto i : b)
        cout << i<<" ";
    std::cout << std::endl;

    return 0;
}



[此贴子已经被作者于2016-6-13 05:11编辑过]

2 回复
#2
哒哒哒啦啦啦2016-06-13 05:29
似乎明白点了,下面这句就是对的,
auto ptr=partition(v.begin(), v.end(), [n](string const a) {return a.size()<=n;});
是不是算法partition要求只能有一个参数(string const a),这句话这么写就报错
auto ptr=partition(v.begin(), v.end(), [n](string const a,string const b) {return a.size()<b.size();});
#3
rjsp2016-06-13 09:01
stable_sort(v.begin(), v.end(), [](string const a, string const b) {return a.size() <b.size(); });
应该是
stable_sort(v.begin(), v.end(), [](string const& a, string const& b) {return a.size() <b.size(); });

你能不能将完整的题目要求贴出来

std::vector<std::string> v
    {
        "1234","1234", "alan","1234","hi~", "alan", "alan", "cp" // 红色是我增加的
    };
为例,输出为 1234 alan 1234 alan,这符合你题目的要求还是不符合?
1