【发布时间】:2015-01-13 17:45:39
【问题描述】:
我有两个类:InitTable 和 InitEntry。 InitTable 包含一个std::map table,它存储一个条目(汽车)的ID,以及代表该汽车的对象(InitEntry)。每个InitEntry 有3个成员变量:
std::string IDdouble speedstd::string heading
我的目标是首先将所有汽车存储在std::map table 中,然后遍历该数据结构,并尝试根据公共属性将汽车组织成集群(std::vector<InitEntry>):speed & @987654331 @。
示例:
假设我们有 6 辆汽车(ID 0 到 8)
- car0:id:“0”,速度:22,航向“N”
- car1:id:“1”,速度:26,航向“N”
- car2:id:“2”,速度:28,航向“W”
- car3:id:“3”,速度:12,航向“E”
- car4:id:“4”,速度:10,航向“E”
- car5:id:“5”,速度:45,航向“S”
为了简单起见,在这个阶段对我来说,仅根据航向对汽车进行分组就足够了。结果是:
std::vector clus1 = {car0, car1}
std::vector clus2 = {car2}
std::vector clus3 = {car3, car4}
std::vector clus4 = {car5}
不幸的是,我没有足够的 C++ STL 知识来理解如何在 C++ 中实现这一点。
InitTable.h:
#include <InitEntry.h>
class InitTable {
public:
InitTable();
virtual ~InitTable();
void clearTable();
void addEntry(std::string ID, double speed, std::string heading);
void deleteEntry(std::string ID);
InitEntry* getEntry(std::string ID);
protected:
std::map<std::string, InitEntry*> table;
};
InitTable.cc:
#include"InitTable.h"
InitTable::InitTable(){}
InitTable::~InitTable()
{
clearTable();
}
void InitTable::clearTable()
{
this->table.clear();
}
void InitTable::addEntry(std::string ID, double speed, std::string heading)
{
InitEntry* newEntry = new InitEntry(ID, speed, heading);
std::cout<< "server::InitTable: vehicle registered to the init table" << newEntry << endl;
table.insert(std::make_pair(ID, newEntry));
}
void InitTable::deleteEntry(std::string ID)
{
InitEntry* ie = getEntry(ID);
if (ie != NULL)
{
table.erase(ID);
delete ie;
}
}
InitEntry* InitTable::getEntry(std::string ID)
{
std::map<std::string, InitEntry*>::iterator it = table.find(ID);
if (it != table.end())
{
return it->second;
}
else
{
std::cout << "such entry does not exist" << endl;
return NULL;
}
}
InitEntry.h:
class InitEntry {
public:
virtual ~InitEntry();
InitEntry(std::string ID, double speed, std::string heading);
std::string getID();
protected:
std::string sumoID;
double speed;
std::string heading;
};
InitEntry.cc:
#include "InitEntry.h"
InitEntry::InitEntry(std::string ID, double speed, std::string heading): ID(ID), speed(speed), heading(heading){}
InitEntry::~InitEntry(){}
std::string InitEntry::getID()
{
return this->ID;
}
编辑 1:添加额外描述(应 @TomaszLewowski 的要求)。
是的,我的目标是将车辆分组,按标题,然后根据速度。因此,最初会有一大群车辆朝着某个方向行驶,后来需要根据速度将其分成更多的集群。假设:车辆向“北”行驶,速度:0 - 20... 速度:40 - 50...等
【问题讨论】:
-
您能更详细地描述一下您想要实现的目标吗?例如您是否寻求“所有具有相同速度/方向的汽车”?在这种情况下,您的 InitEntry 可能不应该是一条记录,而是一个记录向量。或指向一个的引用/指针。
-
注意:您有内存泄漏。在主容器中存储对象(不是新对象)。如果您的对象是多态的,您可以存储 std::uniique_ptr
-
std::map<std::string, InitEntry*> table;为什么不直接使用std::map<std::string, InitEntry>并跳过手动内存管理? -
@TomaszLewowski 是的,你猜对了,这就是我想要实现的目标。
-
@PaulMcKenzie 感谢您的建议。正如我所说,我不是一个非常有经验的程序员,所以欢迎任何建议
标签: c++ dictionary vector stl c++98