【问题标题】:error: no matching function for call to sort错误:没有用于排序调用的匹配函数
【发布时间】:2015-08-22 05:05:27
【问题描述】:

来自 Matthew H. Austern 的 STL 书籍,固定大小数组的“块”类。

template<class T, size_t N>
struct Block
{
   // Various typedef's

   // Implementations of begin() and end().

   reference operator[](size_t nIndex)
   {
     return data[nIndex];
   }

   // I added this overloaded operator+
   T* operator+(const size_t nIncrement)
   {
     return (data + nIncrement);
   }

   // I added this overloaded cast operator
   // **Why is this cast operator not being called?**
   operator T*()
   {
     return data;
   }

   T data[N];
};

这就是我想要做的:

Block<int, 10> tArray; // Populate tArray.

// I want to use std::sort() in the same way as I would
// for a regular array.
sort(tArray, tArray + tArray.size());

我得到编译器错误:

错误:没有匹配的函数调用 sort(Block&, int*)

为什么编译器不知道重载的强制转换运算符?

以下全部编译:

sort(tArray + 0, tArray + tArray.size());
sort(static_cast<int*>(tArray), tArray + tArray.size());
sort(tArray.begin(), tArray.end());

显然,强制转换运算符的重载是有问题的 我不知道的工作。有什么想法吗?

谢谢。

约束:

我可能不会使用 C++11(所以没有来自 C++11 的 std::array)。 我可能不会使用 begin() 或 end()。

【问题讨论】:

  • 在决定模板参数时不考虑转换运算符。如果 sort 不是模板函数,您的代码将起作用。 Cast 运算符通常不是一个好主意,
  • FWIW,有一个 boost::array 就像现在的标准一样工作。
  • 正如上面约翰所说。由于 std::sort 是一个模板函数,它试图从参数中决定模板的类型,并且不知道选择哪个。 sort(tArray, tArray+tArray.size()) 应该可以工作
  • 我认为我能做的最好的事情是:sort(arr, arr+ size);

标签: c++ arrays


【解决方案1】:

您要求可以使用begin()end() 是有问题的。排序需要随机访问迭代器;见Bjarne Stroustrup The C++ programming language 4th editionstd::sort

使用显式转换和指针算法,您应该能够执行以下操作:

例如让 Tstd::string,让 N 为 42,让 b 为初始化的@ 987654331@:

Block<std::string, 42> b;
std::string* begin = (std::string*)b;
std::string* end = begin + 42; // Or if Block has Block.size()
                               // std::string* end = begin + b.size()

std::sort(begin, end);

现在 b 包含根据bool operator&lt;(const std::string&amp;, const std::string&amp;) 排序的字符串。

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 2012-12-28
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多