简体   繁体   English

排序不适用于模板化类

[英]Sorting doesn't work with templated class

I have an insertion sort function我有一个插入排序功能

   void insertionSort(ArrayList<int> myData)
    {

      for (int i = 1; i < myData.getSize(); i++) {

      int index = myData[i];
      int j = i;

      while (j > 0 && myData[j-1] > index) {
         myData.swap(j - 1, j);
         j--;
        }
       myData[j] = index;

      }

    }

which uses this swap function使用此交换功能

   template<class TYPE>
   void ArrayList<TYPE>::swap(int from, int to) throw(std::out_of_range)
  {
     int temp = 0;
     temp = this->items[from];
     this->items[from] = this->items[to];
     this->items[to] = temp;

     swapNum++;
   }

This is how my private methods look like这就是我的私有方法的样子

TYPE * items;
int currentLength;
static int swapNum;

I have an overloaded [] operator and a getSize() function that I think I wrote well and not contributing to my problem.我有一个重载的 [] 运算符和一个 getSize() 函数,我认为我写得很好并且不会导致我的问题。 Now if I do this in my main.cpp现在,如果我在 main.cpp 中执行此操作

     ArrayList<int>m_Data(1);

and append say 4,2,9,1 on the m_Data and call并在 m_Data 上附加说 4,2,9,1 并调用

     insertionSort(m_Data);

I get two errors我有两个错误

    1. Error    C2440   '=': cannot convert from 'std::string' to 'int' 

on the swap function and关于交换函数和

    2. The insertion sort doesn't work

First problem: it should be something like TYPE temp = this->items[from] .第一个问题:它应该类似于TYPE temp = this->items[from] After repairing it (I used STL swap) function works.修复后(我使用 STL 交换)功能工作。 Well, it works on STL vector and swap.嗯,它适用于 STL 向量和交换。 If you still do have problem, then your array structure is probably invalid.如果您仍然有问题,那么您的数组结构可能无效。

EDIT: In function 'insertionSort' shouldn't you have template (as in swap function)?编辑:在函数“insertionSort”中,你不应该有模板(如交换函数)吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 模板化的typedef解决方法似乎不起作用 - Templated typedef workaround doesn't seem to work 模板函数中的静态std :: mutex不起作用 - Static std::mutex in templated function doesn't work 为什么我的排序代码不起作用? - why doesn't my sorting code work? 为什么 Map 中的迭代器排序不起作用 - Why doesn't sorting work for an iterator in Map 为什么派生的模板化类的函数不能覆盖非模板化的基类的纯虚函数? - Why doesn't derived templated class's function override the non-templated base class's pure virtual function? 为什么在模板化类之外返回 std::string 的 constexpr 函数不会编译? - Why doesn't constexpr function returning std::string doesn't compile when outside templated class? 在模板化函数和类中进行T &amp;&amp; - T&& in templated function and class Templatd lambda 调用模板化 lambda (C++20) 不适用于 clang 12 / 13 - Templatd lambda calling templated lambda (C++20) doesn't work with clang 12 / 13 为什么C ++的<vector>模板化类不会破坏一个定义规则? - Why C++'s <vector> templated class doesn't break one definition rule? 无法将模板化函数显式实例化为模板化类 - Can't explicitly instantiate templated function into templated class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM