gpt4 book ai didi

c++ - 带有 lambda 比较器的集合对的 vector

转载 作者:行者123 更新时间:2023-12-02 10:04:26 25 4
gpt4 key购买 nike

我正在尝试制作一组​​成对的 vector :vector<pair<set<int>, set<int>>>但我想为这两组使用不同的 lambda 比较器。
我试着做:

#include <bits/stdc++.h>
using namespace std;

int main() {
auto cmp = [&] (int a, int b) -> bool {
return a > b;
};
auto hi = [&] (int a, int b) -> bool {
return a < b;
};
vector<pair<set<int, decltype(cmp)>, set<int, decltype(hi)>>> lol(cmp, hi);
return 0;
}

但它给了我这个错误:
test.cpp:11:75: error: no matching function for call to ‘std::vector<std::pair<std::set<int, main()::<lambda(int, int)> >, std::set<int, main()::<lambda(int, int)> > > >::vector(main()::<lambda(int, int)>&, main()::<lambda(int, int)>&)’
ype(cmp)>, set<int, decltype(hi)>>> lol(cmp, hi);
^
compilation terminated due to -Wfatal-errors.

另外,还有什么方法可以初始化 vector 的大小吗?
请帮忙。

最佳答案

您正在尝试将 lambdas 传递给外部 vector 的构造函数,它没有将 lambda 作为输入的构造函数。

您需要将 lambdas 传递给 std::set构造函数,这意味着您需要构造单个 std::set实例(见 C++11 std::set lambda comparison function ),然后将它们插入 vector 中,例如:

#include <vector>
#include <set>
#include <utility>
using namespace std;

auto cmp = [] (int a, int b) -> bool {
return a > b;
};

auto hi = [] (int a, int b) -> bool {
return a < b;
};

using set_cmp = set<int, decltype(cmp)>;
using set_hi = set<int, decltype(hi)>;
using set_pair = pair<set_cmp, set_hi>;

int main()
{
vector<set_pair> lol;
...
lol.push_back(make_pair(set_cmp(cmp), set_hi(hi)));
...
return 0;
}

这意味着您将无法预先设置 vector 的大小,因为它需要能够默认构造 set对象,因此您无法将 lambdas 传递给它们。如果需要,请改用无状态仿函数:

#include <vector>
#include <set>
#include <utility>
using namespace std;

struct cmp {
bool operator()(int a, int b) const {
return a > b;
}
};

struct hi {
bool operator()(int a, int b) const {
return a < b;
}
};

using set_cmp = set<int, cmp>;
using set_hi = set<int, hi>;
using set_pair = pair<set_cmp, set_hi>;

int main()
{
vector<set_pair> lol(...desired size...);
...
return 0;
}

关于c++ - 带有 lambda 比较器的集合对的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60961720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com