I have a map that is storing components of a polynomial. The key is the exponent and the value is the coefficient.The map that has integer keys and integer values. I am iterating in my print function, the program crashes when I do my iteration. As I was putting keys into my arrays everything seemed to check out. The input file has this format -1 0 5 1 20 3 -9 2 -2 1 1 2 -2 3 1 9,where every pair is (coefficient, exponent).`
//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;
}