为什么我的std :: map失去了它的价值?

时间:2017-06-27 16:43:24

标签: c++

我有一个类多项式,它有一个成员对象polyMap。

std::map<int,int> polyMap;

Polynomial() {}
Polynomial(const Polynomial& rhs){
    polyMap=rhs.polyMap;
}
~Polynomial() {

}

我正在读取文件中的行并使用一对int填充地图,一个int作为键,另一个作为值。

我使用一个函数从文本文件中填充多个多项式,并填充它们的地图

Polynomial* populateFields(const char* filename) {
ifstream infile(filename);
int i;
int z;
string s;

Polynomial* arr = new Polynomial[numLinesInFile(filename)];
int index = 0;
while (!infile.eof()) {
    getline(infile, s);
    stringstream t(s);
    Polynomial* poly = new Polynomial;
    arr[index] = *poly;
    index = index + 1;
    while (t >> i >> z) {
        poly->polyMap[z] = i;
      }
    }
   return arr;
 }

当我尝试访问main函数中的多项式映射时,其值始终返回零。

为什么我的地图会失去价值?根据我的理解,地图是智能指针,是否在我的populateFields函数末尾调用了地图对象析构函数?

2 个答案:

答案 0 :(得分:3)

在初始化数据之前进行复制:

while (getline(infile, s)) {
    stringstream t(s);
    Polynomial poly;
    while (t >> i >> z) {
        poly.polyMap[z] = i;
    }
    arr[index] = poly;
    index = index + 1;
}

或用std::vector重写:

std::vector<Polynomial> populateFields(const char* filename) {
    std::vector<Polynomial> res;
    std::ifstream infile(filename);
    std::string s;
    while (getline(infile, s)) {
        std::stringstream t(s);

        res.emplace_back();
        Polynomial& poly = res.back();
        int i;
        int z;
        while (t >> i >> z) {
            poly.polyMap[z] = i;
        }
    }
    return res;
 }

答案 1 :(得分:0)

这是另一种方法:

becomeFirstResponder