使用:Eclipse 3.8.1,C / C ++远程调试启动器6.0.0,带GCC 1.1.0和GDB 7.0.0 已验证:Visual Studio 2010
我正在把头发拉出来。使用以下代码时,将始终删除Room对象 rooms 向量的最后一个元素。我无法使用此代码获取除最后一个元素之外的任何元素。我只是想删除一个元素(位置由用户决定)。
我知道很多人可能会问为什么我不使用列表,但随机数据访问比使用此集合添加/删除元素更容易。你有什么想法吗?
void House::removeRoom(unsigned int roomToRemove){
try{
if(roomDoesNotExist(roomToRemove)) throw houseException("Room requested to remove does not exist", roomToRemove, __FILE__, __LINE__);
vector<Room>::iterator roomIterator = rooms.begin() + roomToRemove;
rooms.erase(roomIterator);
removeAllLinksToRoom(roomToRemove);
renumberLinkedRoomsAfterErase(roomToRemove);
}
catch(houseException& hException){
hException.display(cerr);
}
}
以下是House类的片段:
#include "Room.h"
using namespace std;
class House {
public:
vector<Room> rooms;
//member functions
void removeRoom(unsigned int roomToRemove);
//constuctors / destructors
House();
virtual ~House();
//STL linked list overload operators =, ==, and <
House &operator=(const House &rhs);
int operator==(const House &rhs) const;
int operator<(const House &rhs) const;
private:
bool roomDoesNotExist(int roomToRemove);
void removeAllLinksToRoom(int roomToUnlink);
void renumberLinkedRoomsAfterErase(int erasedRoom);
};
因为它可能是相关的,所以我包括了我的整个Room类:
#include "Wall.h"
#include <vector>
#include <algorithm>
#include <string>
#include "exceptions/houseException.h"
using namespace std;
class Room {
public:
float setPointDegF;
vector<Wall> walls; //TODO consider making walls protected / private
private:
string roomName;
vector<int> linkedRooms;
float storedTemperature;
float storedHumidity;
//member functions
void linkToRoom(int roomToLink);
void unlinkFromRoom(int roomToUnlink);
void removeAllLinksToRoom(int roomToUnlink);
void renumberLinkedRoomsAfterErase(int erasedRoom);
public:
//friends
friend class House;
//member functions
void addWalls(unsigned int numWallsToAdd=1);
void removeWall(unsigned int wallToRemove);
//Sensor Functions
void readSensorTemperature();
void readSensorHumidity();
void temperature();
void humidity();
//constuctors / destructors
Room();
virtual ~Room();
//STL linked list overload operators =, ==, and <
Room &operator=(const Room &rhs);
int operator==(const Room &rhs) const;
int operator<(const Room &rhs) const;
private:
void getAttachedRooms(Wall& tempWall);
bool wallDoesNotExist(unsigned int wallToRemove);
bool roomLinked(int roomToLink);
bool roomNotLinked(int roomToLink);
vector<int>::iterator findRoom(int roomToFind);
vector<int>::iterator findInsertionPoint(int roomToInsert);
};
答案 0 :(得分:1)
rooms.erase(roomIterator)
将删除位置roomIterator
处的元素。如果您要从开头roomToRemove
删除所有元素,请使用rooms.erase(rooms.begin(), rooms.begin()+roomToRemove)
或rooms.erase(rooms.begin(), roomIterator)
答案 1 :(得分:1)
牛米。在我的问题下面的评论中回答了这个问题,但为了清楚起见,我在这里重新输入:
此外,Room类是否具有赋值运算符和副本 构造函数定义正确吗? - n.m。
答案:不是。明确的Room类分配操作符导致了该问题。
我试图重载默认赋值运算符并失败 草草收场。当我注释掉该代码并使用隐式&amp; =时 操作员,生活是美好的。问题解决了。 -neghzero