gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:56:38 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com