简体   繁体   中英

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.

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

应该:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM