c++ - 这是排序 ptr_vector 的正确方法吗?

标签 c++

我正在尝试使用 boost 的指针容器,并对其应用 STL 算法。我写了一段代码来排序 ptr_vector<Point>其中Point是一个有成员的类int x, y .代码如下:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

using namespace std;

struct Point {
int x, y;
  Point(int xx, int yy) : x(xx), y(yy) {
   cout << "Point: " << x << " " << y << endl;
  }
 ~Point() {
  cout << "~Point: " << x << " " << y << " this: " << this << endl;
 }
};

struct ComparePoint{
 bool operator() (const Point& p1, const Point& p2) {
  return (p1.x + p1.y < p2.x + p2.y);
 }
};

struct PrintPoint{
 bool operator() (const Point& p) {
  cout << p.x << " " << p.y << endl;
 }
};
int main() {
 boost::ptr_vector<Point> v;
 v.push_back(new Point(1,3));
 v.push_back(new Point(2,0));
 v.push_back(new Point(3,4));
 v.push_back(new Point(4,1));

 //sort(v.begin(), v.end(), ComparePoint());
 for_each(v.begin(), v.end(), PrintPoint());
 return 0;
}

您可能会注意到我注释行“sort(v.begin(), v.end(), ComparePoint())”,在这种情况下输出 (cout) 看起来很正常,如下所示。

Point: 1 3
Point: 2 0
Point: 3 4
Point: 4 1
1 3
2 0
3 4
4 1
~Point: 1 3 this: 0x1d3f010
~Point: 2 0 this: 0x1d3f050
~Point: 3 4 this: 0x1d3f030
~Point: 4 1 this: 0x1d3f070

但是,当我取消注释行“sort(v.begin(), v.end(), ComparePoint())”时,cout 输出如下:

Point: 1 3
Point: 2 0
Point: 3 4
Point: 4 1
~Point: 2 0 this: 0x7fff3f723970
~Point: 3 4 this: 0x7fff3f723960
~Point: 3 4 this: 0x7fff3f723970
~Point: 4 1 this: 0x7fff3f723960
~Point: 4 1 this: 0x7fff3f723970
2 0
1 3
4 1
3 4
~Point: 2 0 this: 0x1e45010
~Point: 1 3 this: 0x1e45050
~Point: 4 1 this: 0x1e45030
~Point: 3 4 this: 0x1e45070

从输出来看,排序没问题,但是多了5次析构调用。那是从哪里来的?更有趣的是,如果我将 sort 改为 stable_sort,输出如下:

Point: 1 3
Point: 2 0
Point: 3 4
Point: 4 1
~Point: 2 0 this: 0x7fffcbe85140
~Point: 4 1 this: 0x7fffcbe85140
~Point: 2 0 this: 0x26010c0
~Point: 1 3 this: 0x26010c8
~Point: 1 3 this: 0x26010d0
~Point: 1 3 this: 0x26010d8
2 0
1 3
4 1
3 4
~Point: 2 0 this: 0x2601010
~Point: 1 3 this: 0x2601050
~Point: 4 1 this: 0x2601030
~Point: 3 4 this: 0x2601070

从输出来看,似乎有两个 Point 实例从堆栈中释放,另外 4 个从堆中释放。由于这种奇怪的行为,我害怕在指针容器上使用算法?你知道如何解释这个吗?或者这是对 ptr_vector 或其他顺序指针容器进行排序的正确方法吗?

最佳答案

您似乎正在使用 std::sort 进行排序,这会交换元素并因此导致调用析构函数。 boost::ptr_containers documentation声明“不幸的是,无法将指针容器与标准库中的变异算法一起使用。但是,最有用的是作为成员函数提供的:”。如果您改为调用 ptr_vector.sort(),我怀疑您不会看到对析构函数的调用。

关于c++ - 这是排序 ptr_vector 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9697339/

相关文章:

c++ - 返回对类静态数据成员的引用的正确方法是什么? (我正在使用 Qt,以防它有所作为)

c++ - 如何在 C++ 中使用 printf

c++ - 使用 GCC 在静态内存中分配 C++ 类

c++ - 最大类型值之间的关系

c++ - 玩家角色的背景颜色 (@) 与其他方 block 重叠

c++ - 字符串到 bool 表达式不起作用 C++

c++ - WSL (Ubuntu) 与 X11、glfw(3) 编程兼容吗?

c++ - 在 Qt HTML5 应用程序中使用替代脚本语言

C++ 如何在 while 循环中正确使用线程

c++ - 我应该使用 std::old_c_functions 还是只使用 old_c_functions?