将元素添加到未存储的c ++类中的向量

时间:2009-11-13 00:43:38

标签: c++ vector scope

编辑:我的调试器对我撒谎。这一切都无关紧要

你好,

我看了Adding element to vector,但这对我的情况没有帮助。

我正在尝试从第三个对象(ClusterManager)向另一个对象(Cluster)添加一个元素(自定义类LatLng)。

当我将LatLng传递给Cluster(ClusterManager.cpp的最后一行)并跳转到Cluster :: addLocation时,在函数执行结束时gdb说我的新LatLng已添加到Cluster中,但是我跳的那一刻回到最高级ClusterManager的范围,添加到向量'locStore'的新LatLng在运行时或调试中都不存在。

有什么想法吗?

DJS。

DE:Xcode 3.2(针对调试10.5) 操作系统:OSX 10.6 编译:GCC 4.2 Arch: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;
};

4 个答案:

答案 0 :(得分:2)

调试器可能在撒谎。我发现Xcode有问题已经查看了向量的内容,尝试使用一些断言来确保有问题的向量实际上被填充。

答案 1 :(得分:0)

LatLng的复制构造函数是什么样的?当您调用std::vector::push_back()时,会在将其添加到向量之前创建参数的副本。缺少非编译器生成的复制构造函数可能表明您没有在目标向量中看到某些值。

另外,您提到在迭代向量内容时遇到越界错误。这表明向量中的元素少于您预期的元素。考虑使用由vector.size()绑定的for循环迭代向量。

答案 2 :(得分:0)

LatLng的复制构造函数有什么作用?这可以确定调用push_back时向量中实际结束的内容。

顺便说一下,使用迭代器而不是向量循环中的索引更有效 - 更少运算符[]用法,更倾向于通过迭代器直接引用向量成员。

答案 3 :(得分:-3)

std :: vector :: push_back()需要一个const引用作为输入,但是你传递的是非const引用,所以编译器必须创建一个临时的LatLng对象,这是添加到向量的而不是你原来的LatLng对象。