sflee
sflee

Reputation: 1719

c++ sorting a vector of pair with a self defined template library

Solved
Thanks, I used David Schwartz's answer and solved the problem. Below is the code that I can use.

The original question I have is how to sort a vector of pair, and I get the answer from here :
Sorting a std::vector<std::pair<std::string,bool>> by the string?

Then I want to keep this method in my library my_lib.hpp, so that I can use it when I needed and also, I want to try to make a template for it.
Following is my setting, and my problem is I get this error in eclipse

undefined reference to void haha::pair_sort_second_dec<std::pair<int, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >(std::vector<std::pair<int, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<int, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&) main.cpp /question line 406 C/C++ Problem

my_lib.hpp

namespace haha{
template <class T>
bool pairCompare_dec(const T& , const T& );
template <class T>
void pair_sort_second_dec(std::vector<T>& );


template <class T>
bool pairCompare_dec(const T& firstElem,const T& secondElem) {
  return firstElem.second > secondElem.second;
}
template <class T>
void pair_sort_second_dec(std::vector<T>& target){
    std::sort(target.begin(),target.end(),pairCompare_dec<T>);
}
};

main.cpp

#include "my_lib.hpp"

int main(int argc,char* argv[]){
    std::vector<std::pair<int,std::string> > test;
    // initial test
    haha::pair_sort_second_dec(test);
    return 0;
}

Anyone knows how to fix it? Thanks in advance.

Upvotes: 0

Views: 135

Answers (1)

David Schwartz
David Schwartz

Reputation: 182875

std::sort(target.begin(),target.end(),pairCompare_dec);

Should be:

std::sort(target.begin(),target.end(),pairCompare_dec<T>);

Upvotes: 2

Related Questions