编辑:我的调试器在骗我。这都是无关紧要的
大家好
我偷看了Adding element to vector ,但这对我的情况没有帮助。
我正在尝试从第三个对象 (ClusterManager) 向另一个对象 (Cluster) 添加一个元素(自定义类 LatLng)。
当我将 LatLng 传递给 Cluster(ClusterManager.cpp 的最后一行)并跳转到 Cluster::addLocation 时,在函数执行结束时 gdb 说我的新 LatLng 已添加到 Cluster,但是当我跳转时回到最高类 ClusterManager 的范围,添加到 vector “locStore”的新 LatLng 在运行时或调试中都不存在。
有什么想法吗?
音乐总监。
DE:Xcode 3.2(针对调试 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();
};
集群.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;
};
最佳答案
调试器可能在说谎。我发现 Xcode 在查看 vector 的内容时遇到问题,请尝试使用一些断言来确保所讨论的 vector 确实已被填充。
关于c++ - 将元素添加到未存储的 c++ 类中的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1726425/