[英]vector of pair of set with lambda comparator
我正在嘗試制作一組成對的vector<pair<set<int>, set<int>>>
: 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.
另外,有什么方法可以初始化向量的大小嗎? 請幫忙。
您正在嘗試將 lambdas 傳遞給外部vector
的構造函數,該構造函數沒有將 lambdas 作為輸入的構造函數。
您需要將 lambdas 傳遞給std::set
構造函數,這意味着您需要構造單個std::set
實例(請參閱C++11 std::set lambda 比較函數),然后將它們推入向量中,例如:
#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;
}
這意味着您將無法預先確定向量的大小,因為它需要能夠默認構造set
對象,因此您無法將 lambda 傳遞給它們。 如果需要,請改用無狀態函子:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.