简体   繁体   中英

Iterating through map C++

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

The line

map<int, int>* pol = new map<int, int>;

is the culprit. It creates a function local variable. It does not set the value of the member variable. As a consequence, the member variable of the same name remains uninitialized. Dereferencing that variable in other functions causes undefined behavior.

Change that line to:

pol = new map<int, int>;

As was suggested in one of the comments, I would strongly advise changing that member variable from a pointer to an object. You get automatic memory management from using an object. You don't need to worry about using new to allocate memory for it and using delete to deallocate memory used by it. Not only that, if you take on the job of allocating memory in your class, you need to know about The Rule of Three and make sure your class confirms to those rules.

If you are using a C++11 compiler, The Rule of Three becomes the The Rule of Five .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM