[英]Passing vector in template argument
我想定義一個比較函數,以便可以將其傳遞給std :: sort。 需要根據向量x的順序進行比較,如下面的“ compare_by_x”函數所示。
template <std::vector<double> x>
bool compare_by_x(int i, int j){
return x[i] <= x[j];
}
我想按如下方式傳遞compare_by_x函數。 這是行不通的。
std::sort(some_index_vector.begin(), some_index_vector.end(), compare_by_x<x>);
您不能將對象引用傳遞給模板或函數。 但是您可以將它們傳遞給結構。
這是工作示例:
#include <iostream>
#include <vector>
#include <algorithm>
struct compare_by_x
{
std::vector<double>& x;
compare_by_x(std::vector<double>& _x) : x(_x) {}
bool operator () (int i, int j)
{
return x[i] <= x[j];
}
};
int main(int argc, const char *argv[])
{
std::vector<double> some_index_vector;
some_index_vector.push_back(0);
some_index_vector.push_back(1);
some_index_vector.push_back(2);
std::vector<double> x;
x.push_back(3);
x.push_back(1);
x.push_back(2);
std::sort(some_index_vector.begin(), some_index_vector.end(), compare_by_x(x));
for (std::vector<double>::const_iterator it = some_index_vector.begin(); it != some_index_vector.end(); ++it)
{
std::cout << *it << ' ';
}
std::cout << std::endl;
return 0;
}
您根本無法做到這一點–模板僅適用於類型和一些編譯時常量。
您需要看一下std::sort
的文檔,該文檔解釋了期望將哪種比較功能作為第三個參數。 即使模板奇跡般地編譯,您的模板也不起作用。
幸運的是,您的問題的解決方案已經發布在Stack Overflow上 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.