2013-06-28 3 views
0

std :: sort에 전달할 수 있도록 compare 함수를 정의하고 싶습니다. 비교는 아래의 'compare_by_x'함수에서 설명한대로 벡터 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

개체 참조를 템플릿이나 함수로 전달할 수 없습니다. 하지만 struct에 전달할 수 있습니다.

#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.

관련 문제