Setter 不更改 class 中矢量的数据

Setter not changing the data from a vector within a class

在我的程序中,我有一个 class 包含一个整数类型的向量。它用于存储距离。我有一个函数,调用时应将向量中的值设置为 0。 (用于初始化)。但是当我去检查vector的大小时,它仍然说vector是空的。

我创建了多个函数来检查向量是否正在添加任何元素,但事实并非如此。我有一个函数,在 main 中,我调用它来查看向量是否为空,并且它 returns 0(向量中有 0 个元素)。

int MLB::getDistanceSize()
{
    return distances.size();
}

void MLB::setInitialDistances(int size)
{
    for(int i = 0; i < size; i++)
    {
        this->distances.push_back(0);
    }
}
class MLB
{
public:
    //constructor
    MLB();
    ~MLB();

    int getDistanceSize();
    void setInitialDistances(int size);

private:
    vector<int> distances;
};

输入文件是一个csv文件,每行包含:

stadium1,stadium2,距离

所以样本输入文件是:

AT&T Park,Safeco Field,680
AT&T Park,Oakland–Alameda County Coliseum,50
Angel Stadium,Petco Park,110
Angel Stadium,Dodger Stadium,50
Busch Stadium,Minute Maid Park,680
Busch Stadium,Great American Ball Park,310
Busch Stadium,Target Field,465
Busch Stadium,Kauffman Stadium,235

等...

我正在使用 qt,这是我自己调用函数的地方。所有信息都存储在地图中,其他吸气剂工作得很好。很抱歉让这个问题比实际问题更令人困惑,非常感谢任何帮助。

// key and value, key is the team name, value is the MLB stadium information
struct entry
{
    string key;
    MLB value;
};

class Map
{
    public:
        //Public default constructor
        Map();

        //Public default destructor
        ~Map();

        // returns entry of the map
        entry atIndex(int index);

        // Inserts a key and its value using linear algorithm
        void insert(const string& theKey, const MLB& value);

    private:

    vector<entry> thisTable;
    int currentSize;    //Integer variable for current size
};

地图函数:

Map::Map()
{
    currentSize = 0;
}

Map::~Map()
{
}

void Map::insert(const string& theKey, const MLB& value)
{
    entry thisEntry;
    thisEntry.key = theKey;
    thisEntry.value = value;

    thisTable.push_back(thisEntry);

    currentSize+=1;
}

entry Map::atIndex(int index)
{
    return thisTable.at(index);
}
//mainwindow constructor
mainWindow::mainWindow()
{

    //Reads in input from first csv file, all works fine all data stored and can access it

    string iStadium1;
    string iStadium2;
    string iDistance;
    string previous;
    int distance;
    int index1;
    int index2;
    bool found;

    ifstream csvFile2;
    csvFile2.open("inputDistance.csv");

    getline(csvFile2, iStadium1, ',');
    while(!csvFile2.eof())
    {
        index1 = 0;
        found = false;
        while(!found)
        {
            if(thisMap.atIndex(index1).value.getStadiumName() == iStadium1)
            {
                thisMap.atIndex(index1).value.setInitialDistances(thisMap.mapSize());
                cout << "Distance Size Test 1: " << thisMap.atIndex(index1).value.getDistanceSize() << endl;
                found = true;
            }
            else
            {
                index1++;
            }
        }

        previous = iStadium1;

        while(iStadium1 == previous)
        {
            getline(csvFile2, iStadium2, ',');
            getline(csvFile2, iDistance, '\n');
            distance = stoi(iDistance);

            index2 = 0;
            found = false;

            while(!found)
            {
                if(thisMap.atIndex(index2).value.getStadiumName() == iStadium2)
                {
                    found = true;
                    cout << "Distance Size Test 2: " << thisMap.atIndex(index1).value.getDistanceSize() << endl;
                    // crashes here. Index out of bounds, size is 0 for some reason
                    thisMap.atIndex(index1).value.setDistance(index2, distance);
                }
                else
                {
                    index2++;
                }
            }
            getline(csvFile2, iStadium1, ',');
        }
    }

    csvFile2.close();
}

我希望该向量包含 30 个值为 0 的槽(假设传递给函数的所需大小为 30),而不是空向量。

您问题中的代码在添加构造函数和析构函数(两者都不做)后按预期工作:

#include <iostream>
#include <vector>
using namespace std;

class MLB
{
public:
    //constructor
    MLB();
    ~MLB();

    int getDistanceSize();
    void setInitialDistances(int size);

private:
    vector<int> distances;
};

int MLB::getDistanceSize()
{
    return distances.size();
}

void MLB::setInitialDistances(int size)
{
    for(int i = 0; i < size; i++)
    {
        this->distances.push_back(0);
    }
}

MLB::MLB() {
}

MLB::~MLB() {
}


int main()
{
  MLB mlb;

  mlb.setInitialDistances(30);
  cout << mlb.getDistanceSize() << endl;
}

pi@raspberrypi:/tmp $ g++ d.cc
pi@raspberrypi:/tmp $ ./a.out
30

向量不为空但包含 0 的 30 次


如果 thisMap.atIndex(index1).value.setDistance(index2, distance); 什么都不做,这可能是因为 atIndex(index1) return 是一个副本而不是引用,所以你修改了一个副本和原样不变

例如:

#include <iostream>
#include <vector>
using namespace std;

class C {
  public:
    vector<int> getv() { return v; } // return a copy
    vector<int> & getvref() { return v; } // return the ref to the vector, not a copy
    int len() { return v.size(); }

  private:
    vector<int> v;
};

int main()
{
  C c;

  c.getv().push_back(0); // modify a copy of v
  cout << c.len() << endl;

  c.getvref().push_back(0); // modify v
  cout << c.len() << endl;
}

编译与执行:

pi@raspberrypi:/tmp $ g++ vv.cc
pi@raspberrypi:/tmp $ ./a.out
0
1

你编辑了你的问题,这就是我的假设:

entry Map::atIndex(int index)
{
    return thisTable.at(index);
}

return一份,必须

entry & Map::atIndex(int index)
{
    return thisTable.at(index);
}