[英]Iterating through map C++
我有一个存储多项式分量的映射。 键是指数,值是系数。具有整数键和整数值的映射。 我正在迭代打印功能,执行迭代时程序崩溃。 当我将键放入数组时,所有内容似乎都已签出。 输入文件的格式为-1 0 5 1 20 3 -9 2 -2 1 1 2 2 -2 3 1 9,其中每对都是(系数,指数)。
//header
#ifndef poly_h
#define poly_h
#include <map>
class poly {
private:
std::map<int, int>* pol;
public:
poly(char* filename);
poly& operator+(poly& rhs);
poly& operator-(poly& rhs);
poly& operator*(poly& rhs);
void print();
~poly();
};
#endif
//cpp file
#include "poly.h"
#include <iostream>
#include <fstream>
using namespace std;
poly::poly(char* filename)
{
map<int, int>* pol = new map<int, int>;
ifstream input_file;
input_file.open("input.txt");
int coe;
int exp;
while (input_file >> coe) {
input_file >> exp;
cout << coe << " ^" << exp << " ";
map<int, int>::iterator it = pol->find(exp);
if (it == pol->end()) {
(*pol)[exp] = coe;
}
else {
(*pol)[exp] += coe;
if ((*pol)[exp] == 0) {
pol->erase(it);
}
}
cout << (*pol)[exp];
//print();
cout << endl;
}
input_file.close();
}
void poly::print()
{
cout << "inside print<<endl;
for (map<int, int>::iterator outer_iter = pol->begin(); outer_iter != pol->end(); ++outer_iter);
cout << "done";
}
poly::~poly()
{
delete pol;
}
线
map<int, int>* pol = new map<int, int>;
是罪魁祸首。 它创建一个函数局部变量。 它不设置成员变量的值。 结果,具有相同名称的成员变量将保持未初始化状态。 在其他函数中取消引用该变量会导致未定义的行为。
将该行更改为:
pol = new map<int, int>;
正如其中一项评论中所建议的那样,我强烈建议将成员变量从指针更改为对象。 您可以通过使用对象来进行自动内存管理。 您无需担心使用new
为其分配内存,而使用delete
取消分配它所使用的内存。 不仅如此,如果您要在类中分配内存,还需要了解“三条规则”,并确保您的班级遵循这些规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.