C++ 将元素添加到c++;未存储的类
编辑:我的调试器在骗我。这一切都无关紧要 大家好 我看了一眼,但对我的案子没有帮助 我试图从第三个对象(ClusterManager)向另一个对象(集群)添加一个元素(自定义类LatLng) 当我将LatLng传递到Cluster(ClusterManager.cpp的最后一行)并跳入Cluster::addLocation时,在函数执行结束时,gdb表示我的新LatLng已添加到Cluster,但当我跳回最高类ClusterManager的范围时,添加到向量“locStore”的新LatLng在运行时或调试中都不存在 有什么想法吗 DJ DE:Xcode 3.2(针对调试10.5) 操作系统:OSX 10.6 编译器:GCC4.2 拱门:x86_64 ClusterManager.cpp(所有调用的位置):C++ 将元素添加到c++;未存储的类,c++,vector,scope,C++,Vector,Scope,编辑:我的调试器在骗我。这一切都无关紧要 大家好 我看了一眼,但对我的案子没有帮助 我试图从第三个对象(ClusterManager)向另一个对象(集群)添加一个元素(自定义类LatLng) 当我将LatLng传递到Cluster(ClusterManager.cpp的最后一行)并跳入Cluster::addLocation时,在函数执行结束时,gdb表示我的新LatLng已添加到Cluster,但当我跳回最高类ClusterManager的范围时,添加到向量“locStore”的新LatLng
std::vector::push_back()需要一个常量引用作为输入,但您要传递一个非常量引用,因此编译器必须创建一个临时LatLng对象,它是添加到向量而不是原始LatLng对象的对象。类的复制构造函数是什么样的?调用
std::vector::push_back()
时,将在将参数添加到向量之前复制参数。缺少非编译器生成的复制构造函数可能表明为什么在目标向量中看不到某些值
另外,您提到在迭代向量的内容时会出现越界错误。这表明向量中的元素比您预期的要少。考虑使用一个for循环迭代向量,绑定到<代码> vector .siz()/< > > /p> LaTLNG的复制构造函数是什么?这决定了在调用push_back时,向量中实际包含的内容
顺便说一句,在向量循环中使用迭代器比使用索引更为有效-更少的运算符[]使用,有利于通过迭代器直接引用向量成员。调试器可能在撒谎。我发现Xcode在查看向量的内容时存在问题,请尝试使用一些断言来确保所讨论的向量实际上已被填充。您应该知道
这个->x
在绝大多数情况下都可以编写x
。我知道,但我用它来帮助我在头脑中跟踪变量的去向。你所说的“ClusterManager,它不在哪里可以看到”到底是什么意思。您是否在运行时看到问题,或者调试器只是在查看该变量时遇到问题?当我std::cout所有集群中LatLngs的ID时,我在每个集群中的locStore向量上都会出现越界错误。这听起来像是没有正确迭代向量。引用会自动转换为常量引用。将LatLng
对象的副本插入到向量中,但不创建临时对象。这是不正确的。编译器只是将可变引用以静默方式强制转换为常量引用并使用它。
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] );
}
}
#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);
};
#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::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;
};