【发布时间】:2009-11-13 00:43:37
【问题描述】:
编辑:我的调试器在骗我。这都无关紧要
大家好,
我看过Adding element to vector,但这对我的情况没有帮助。
我正在尝试将元素(自定义类 LatLng)从第三个对象(ClusterManager)添加到另一个对象(Cluster)。
当我将我的 LatLng 传递给 Cluster(ClusterManager.cpp 的最后一行)并跳转到 Cluster::addLocation 时,在函数执行结束时,gdb 说我的新 LatLng 已添加到 Cluster,但在我跳转的那一刻回到最高类 ClusterManager 的范围,添加到向量“locStore”的新 LatLng 在运行时或调试中都不存在。
有什么想法吗?
DJ。
DE:Xcode 3.2(针对 Debug 10.5) 操作系统:OSX 10.6 编译器:GCC 4.2 拱门:x86_64
ClusterManager.cpp(调用它的地方):
void ClusterManager::assignPointsToNearestCluster()
{
//Iterate through the points.
for (int i = 0; i < locationStore.size(); i++)
{
double closestClusterDistance = 100.1;
// Make sure to chuck the shits if we don't find a cluster.
int closestCluster = -1;
int numClusters = clusterStore.size();
// Iterate through the clusters.
for (int j = 0; j < numClusters; j++) {
double thisDistance = locationStore[i].getDistanceToPoint( *(clusterStore[j].getCentroid()) );
// If there's a closer cluster, make note of it.
if (thisDistance < closestClusterDistance) {
closestClusterDistance = thisDistance;
closestCluster = j;
}
}
// Remember the penultiment closest cluster.
this->clusterStore[closestCluster].addLocation( this->locationStore[i] );
}
}
ClusterManager.h
#include "Cluster.h"
#include "LatLng.h"
#include <vector>
class ClusterManager{
private:
std::vector<Cluster> clusterStore;
std::vector<LatLng> locationStore;
public:
ClusterManager();
void assignPointsToNearestCluster();
void addLocation(int,double,double);
};
Cluster.h:
#include <vector>
#include <string>
#include "LatLng.h"
class Cluster {
private:
std::vector<LatLng> locStore;
LatLng newCentroid;
bool lockCentroid;
int clusterSize;
int clusterID;
public:
Cluster(int,LatLng&);
void addLocation(LatLng&);
LatLng* getCentroid();
};
Cluster.cpp
Cluster::Cluster(int newId, LatLng &startPoint)
{
this->clusterID = newId;
this->newCentroid = startPoint;
};
void Cluster::addLocation(LatLng &newLocation)
{
(this->locStore).push_back( newLocation );
};
LatLng* Cluster::getCentroid()
{
return &newCentroid;
};
【问题讨论】:
-
您应该知道
this->x在绝大多数情况下都可以写成x。 -
我知道,但我用它来帮助我跟踪变量的去向。
-
您所说的“ClusterManager,它无处可寻”到底是什么意思。您是在运行时发现问题,还是调试器只是在查看该变量时遇到问题?
-
当我对所有集群中的 LatLngs 的 ID 进行 std::cout 时,我在每个集群中的 locStore 向量上出现超出范围的错误。
-
这听起来好像你没有正确地迭代向量。