Setter不会更改类中矢量的数据

问题描述 投票:1回答:1

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

我创建了多个函数来检查向量是否添加任何元素,而不是。我有一个函数,在main中,我调用以查看向量是否为空,并返回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,这就是我自己调用函数的地方。所有信息都存储在地图中,其他的getter工作得非常好。很抱歉让这个问题比实际问题更令人困惑,非常感谢任何帮助。

// 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个槽(假设传递到函数中的所需大小为30),值为0,而不是具有空向量。

c++ qt class vector setter
1个回答
2
投票

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

#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

向量不为空但包含30次0


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

例如 :

#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);
}

必须是复印件

entry & Map::atIndex(int index)
{
    return thisTable.at(index);
}
© www.soinside.com 2019 - 2024. All rights reserved.