【发布时间】:2016-06-24 21:28:11
【问题描述】:
我有一个存储多项式分量的地图。键是指数,值是系数。具有整数键和整数值的映射。我在我的打印功能中进行迭代,当我进行迭代时程序崩溃了。当我将钥匙放入我的阵列时,一切似乎都已检查完毕。输入文件的格式为 -1 0 5 1 20 3 -9 2 -2 1 1 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;
}
【问题讨论】:
-
std::map<int,int> *pol;-- 不需要 this 作为指针,然后使用new和delete。您只需要std::map<int, int> pol;。另外,你能清理一下格式吗?到处都是,很难阅读您的代码。 -
另外,请发一个minimal reproducible example,意思是
main函数。原因是我可以用一个简单的 2 行或 3 行程序轻松破坏您的程序(这都是由于我提到的指针)。此外,operator+、- 和 * 应该返回一个新的poly对象,而不是引用。 -
cout
-
感谢您的帮助。下次我肯定会有更好的格式。
标签: c++ dictionary iterator