[英]Make a vector of comparator functions
我的問題是測試具有不同比較器功能的quicksort的實現: std::less
和std::greater
。 但是我不想復制粘貼僅在兩個比較器中不同的測試代碼,因此我想將它們放入向量(或其他東西)中並對其進行迭代。
為了簡化這篇文章,可以說我想在兩個函數的向量上編寫一個循環,這些函數以0
和1
作為參數並輸出一個布爾值。 這是我的看法:
#include <iostream>
#include <vector>
#include <functional>
int main() {
auto fs = std::vector<>{std::less<int>{}, std::greater<int>{}};
for (auto f: fs) {
std::cout << f(0, 1) << " ";
} std::cout << std::endl;
}
我的g++ 6.1.1
編譯器正確地抱怨我沒有為向量指定模板參數。 我一直在嘗試諸如std::function<bool(int, int)>
而其他方法都沒有運氣。
您能告訴我如何修復這段代碼嗎?
更新:我得到的確切錯誤:
% g++ -std=c++14 -Wall deleteme.cpp && ./a.out
deleteme.cpp: In function ‘int main()’:
deleteme.cpp:6:27: error: wrong number of template arguments (0, should be at least 1)
auto fs = std::vector<>{std::less<int>{}, std::greater<int>{}};
^
In file included from /usr/include/c++/6.1.1/vector:64:0,
from deleteme.cpp:2:
/usr/include/c++/6.1.1/bits/stl_vector.h:214:11: note: provided for ‘template<class _Tp, class _Alloc> class std::vector’
class vector : protected _Vector_base<_Tp, _Alloc>
^~~~~~
deleteme.cpp:8:18: error: unable to deduce ‘auto&&’ from ‘fs’
for (auto f: fs) {
^~
僅從C ++ 17開始,構造函數的模板參數可用於推斷類型的模板參數,因此您將必須編寫std::vector<std::function<bool(int,int)>>
而不是std::vector<>
。
請注意,與直接調用函數相比, std::function
具有性能開銷,因此您可能需要檢查可變參數模板參數(並吞下 )以獲取最后幾個百分比
當您使用不同的類型時,您可能會使用元組,並遍歷元組:
namespace detail {
template <typename F, typename TUPLE, std::size_t ... Is>
void run_for_each(F&& f, TUPLE&& t, std::index_sequence<Is...>)
{
const int dummy[] = {0, (f(std::get<Is>(std::forward<TUPLE>(t))), void(), 0)...};
static_cast<void>(dummy); // Avoid warning for unused variable
}
}
template <typename F, typename TUPLE>
void run_for_each(F&& f, TUPLE&& t)
{
detail::run_for_each(std::forward<F>(f),
std::forward<TUPLE>(t),
std::make_index_sequence<
std::tuple_size<std::decay_t<TUPLE>>::value>());
}
接着
int main() {
auto t = std::make_tuple(std::less<int>{}, std::greater<int>{});
run_for_each([](auto&&f) {std::cout << f(0, 1) << " ";}, t);
std::cout << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.