c++ - 将元素添加到未存储的 c++ 类中的 vector

标签 c++ vector scope

编辑:我的调试器在骗我。这都是无关紧要的

大家好

我偷看了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/

相关文章:

r - 使用并行函数时的环境和范围

c++ - 有条件地构造没有默认构造函数的成员对象

c++ - 仅在一个字符串 lex 处识别开始条件

c++ - 我希望类模板只有在传递给模板的类型为int时才具有sort方法

C++ 部分填充数组,删除赔率值

c++ - 使用 std::find 在 std::vector 中查找 std::tuple

objective-c - 具有本地方法作用域的实例变量

pointers - Golang、指针、函数

c++ - void* 到 vector

c++ - 遍历没有开始和结束的 vector