【问题标题】:How to handle a vector of template class?如何处理模板类的向量?
【发布时间】:2014-07-16 23:51:04
【问题描述】:

我正在开发一个快速排序函数,该函数对从模板创建的对象向量进行排序。特别是 n 维空间上的点向量。这是我的点模板:

#ifndef POINT_H   
#define POINT_H   
template <int dimention, typename type>   
class Point{
public:
    Point(){mCoords = new type[dimention];}
    Point(type* pCoords);
    int getDimention(){return dimention;}
// Operators
//-----------

这是快速排序功能(我没有写实际的实现,因为我想先解决这个问题):

#ifndef QUICK_S
#define QUICK_S
#include <vector>
#include "point.h"

// Generic quicksort function that works with points of any dimention
std::vector<Point<int dimention, typename type> > 
quicksort(std::vector<Point<int dimention, typename type> > unsorted)
{
// implementation --------------

我遇到的错误(其中一些):

In file included from convexHull.cpp:4:0:
quicksort.h:7:47: error: wrong number of template arguments (1, should be 2)

In file included from quicksort.h:4:0,
             from convexHull.cpp:4:
point.h:5:7: error: provided for ‘template<int dimention, class type> class Point’
 class Point{

In file included from convexHull.cpp:4:0:
quicksort.h:7:49: error: template argument 1 is invalid
std::vector<Point<int dimention, typename type> >

如果您能指出我的错误之处,我将不胜感激,欢迎任何提示或想法,我是一个自学成才的程序员。谢谢。

【问题讨论】:

  • 你明白C++已经有std::sort了吧?
  • @MooingDuck 点需要从坐标X、Y、Z等到第n维进行字典排序。 std::sort 可以吗?
  • @GilLázaro 您可以将自定义比较器传递给sort
  • @user657267 Point 类已经有一个覆盖的 std::sort会做得很好。
  • @GilLázaro:是的,如果你有operator&lt;,那么你应该能够“对它进行排序”。或者:coliru.stacked-crooked.com/a/041681fcc2aa0f16

标签: c++ templates vector stl


【解决方案1】:

因为quicksort 可以对vector&lt;Point&lt;int dimention, typename type&gt; &gt; 操作dimentiontype 的任何值,所以它是一个模板函数,必须这样声明:

template<int dimention, typename type>
std::vector<Point<dimention, type> > 
quicksort(std::vector<Point<dimention, type> > unsorted)

还要注意Point&lt;dimention, type&gt; 中的inttypename 在此处被删除。

【讨论】:

  • 还可能值得一提的是,提议的排序不太可能比std::sort 表现更好。我倾向于不写它。
  • @Edward 很有可能会比std::sort 更糟,c 库quicksort 总是如此。
  • 而且,通过按值传递向量,无论如何,您不会对副本进行排序......
【解决方案2】:

你的快速排序定义应该像这样声明它的模板:

std::vector<typename type> 
quicksort(std::vector<type> unsorted)
{
// implementation --------------

每当您调用快速排序时,都会为您的特定点设置添加模板:

quicksort<Point<1,float> >(pointList);

根据 Mooing Duck 的评论,在这种情况下,您不需要提供模板类型,因为它可以由编译器推断:

quicksort(pointList);

应该是你所需要的。

【讨论】:

  • 这种情况下不需要显式指定模板参数,可以推导出来。
  • 我想在这种情况下也是如此。
猜你喜欢
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多