我的ptBucket.getBucket()。at(icnt)如何工作,但是我的ptBucket.getBucket()。erase()和ptBucket.getBucket()。begin()无法工作。
代码如下。
我想要一个包含指针向量的对象。指针将指向动态分配的对象,最后我要清理。我似乎正在搞砸间接的额外水平。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Pt{
int x_;
int y_;
public:
Pt(int x, int y);
int getX();
int getY();
};// end class pt
Pt::Pt(int x, int y){
x_ = x;
y_ = y;
}
int Pt::getX(){
return x_;
}
int Pt::getY(){
return y_;
}
class BucketOfPts{
vector<Pt*>bucket;
public:
void addToBucket(Pt *pt);
vector<Pt*> getBucket();
};
void BucketOfPts::addToBucket(Pt *pt){
bucket.push_back(pt);
}
vector<Pt*> BucketOfPts::getBucket(){
return bucket;
}
int main()
{
cout << "this works" << endl;
vector<Pt*> points;
for(unsigned icnt =0;icnt<5;icnt++)
points.push_back(new Pt(icnt,icnt));
for(unsigned icnt =0;icnt<5;icnt++)
cout << "x of icnt["<<icnt<<"] "<< points.at(icnt)->getX() << endl;
for(unsigned icnt =0;icnt<5;icnt++)
{
/*** this simple construct does work ***********/
points.erase(points.begin());
/*** this simple construct does work ***********/
cout << "size: " << points.size() << endl;
}
cout << "this does NOT work" << endl;
BucketOfPts ptBucket = BucketOfPts();
for(unsigned icnt =0;icnt<5;icnt++)
ptBucket.addToBucket(new Pt(icnt,icnt));
for(unsigned icnt =0;icnt<5;icnt++)
cout << "x of icnt["<<icnt<<"] "<< ptBucket.getBucket().at(icnt)->getX() << endl;
// how come ptBucket.getBucket.at() above works
// but ptBucket.getBucket.begin() below does not work??
cout << "going to try to erase" << endl;
for(unsigned icnt =0;icnt<5;icnt++)
{
cout << "going to erase icnt: " << icnt << endl;
/*** this simple construct does NOT work ***********/
ptBucket.getBucket().erase(ptBucket.getBucket().begin());
/*** this simple construct does NOT work ***********/
cout << "size: " << ptBucket.getBucket().size() << endl;
}
return 0;
}
here's my output:
this works
x of icnt[0] 0
x of icnt[1] 1
x of icnt[2] 2
x of icnt[3] 3
x of icnt[4] 4
size: 4
size: 3
size: 2
size: 1
size: 0
this does NOT work
x of icnt[0] 0
x of icnt[1] 1
x of icnt[2] 2
x of icnt[3] 3
x of icnt[4] 4
going to try to erase
going to erase icnt: 0
Segmentation fault (core dumped)
最佳答案
照原样,您的getBucket()
函数将返回vector<Pt*> bucket;
成员的副本。因此,声明
ptBucket.getBucket().erase(ptBucket.getBucket().begin());
只能使用该向量的两个不相关的副本进行操作。
要使类实例中的vector成员受影响,您需要返回对此成员的引用
class BucketOfPts{
public:
// ...
vector<Pt*>& getBucket();
// ^ <<<<<<
};
vector<Pt*>& BucketOfPts::getBucket() {
// ^ <<<<<<
return bucket;
}
`