【问题标题】:c++ sorting a vector of pair with a self defined template libraryc ++使用自定义模板库对对向量进行排序
【发布时间】:2014-01-22 06:11:50
【问题描述】:

已解决
谢谢,我使用了大卫施瓦茨的答案并解决了这个问题。以下是我可以使用的代码。

我最初的问题是如何对一对向量进行排序,我从这里得到答案:
Sorting a std::vector<std::pair<std::string,bool>> by the string?

然后我想将这个方法保存在我的库 my_lib.hpp 中,以便我可以在需要时使用它,并且我想尝试为它制作一个模板。
以下是我的设置,我的问题是我在 eclipse 中得到这个错误

未定义引用void haha::pair_sort_second_dec&lt;std::pair&lt;int, std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt; &gt;(std::vector&lt;std::pair&lt;int, std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;, std::allocator&lt;std::pair&lt;int, std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt; &gt; &gt;&amp;)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>);
}
};

ma​​in.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;
}

有人知道怎么解决吗?提前致谢。

【问题讨论】:

  • "undefined reference to [function-name]" 不是错误的精确文本,因为这里没有任何名为 [function-name] 的内容。当询问涉及错误消息的问题时,您必须准确地引用错误消息。
  • 而且错误肯定也表明了一个位置。包括它并说明它对应于所示代码的哪一部分。
  • @JanHudec 对不起,我已经添加了错误信息

标签: c++ templates


【解决方案1】:
std::sort(target.begin(),target.end(),pairCompare_dec);

应该是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2014-06-13
    • 1970-01-01
    相关资源
    最近更新 更多