使用:Eclipse 3.8.1、C/C++ Remote Debug Launcher 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);
};