2013-06-28 72 views
0

我想定義一個比較函數,以便它可以傳遞給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>); 
+0

什麼是'compare_by_x '的X? – mattn

+2

你在編譯時遇到錯誤嗎? – satishgoda

+0

[boost zip \ _iterator和std :: sort]可能重複(http://stackoverflow.com/questions/9343846/boost-zip-iterator-and-stdsort) –

回答

4

您無法將對象引用傳遞給模板或執行功能。 但是你可以將它們傳遞給結構。

這裏是工作示例:

#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; 
} 
+0

太棒了。謝謝! –

1

你根本無法這麼做 - 模板僅適用於類型和一些編譯時常量。

你需要看看documentation of std::sort,它解釋了什麼樣的比較函數可以作爲第三個參數。即使模板做了奇蹟般的編譯,你也不會工作。

幸運的是,你的問題的解決方案has already been posted on Stack Overflow