【问题标题】:Iterating through map C++遍历 map C++
【发布时间】: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&lt;int,int&gt; *pol; -- 不需要 this 作为指针,然后使用 newdelete。您只需要std::map&lt;int, int&gt; pol;。另外,你能清理一下格式吗?到处都是,很难阅读您的代码。
  • 另外,请发一个minimal reproducible example,意思是main函数。原因是我可以用一个简单的 2 行或 3 行程序轻松破坏您的程序(这都是由于我提到的指针)。此外,operator+、- 和 * 应该返回一个新的 poly 对象,而不是引用。
  • cout
  • 感谢您的帮助。下次我肯定会有更好的格式。

标签: c++ dictionary iterator


【解决方案1】:

线

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

是罪魁祸首。它创建一个函数局部变量。它不设置成员变量的值。因此,同名的成员变量保持未初始化状态。在其他函数中取消引用该变量会导致未定义的行为。

将该行更改为:

pol = new map<int, int>;

正如其中一个 cmets 所建议的,我强烈建议将该成员变量从指向对象的指针更改。您可以通过使用对象获得自动内存管理。您无需担心使用new 为其分配内存并使用delete 释放它使用的内存。不仅如此,如果您在班级中承担分配内存的工作,您需要了解The Rule of Three 并确保您的班级遵守这些规则。

如果您使用的是 C++11 编译器,The Rule of Three 将变为 The Rule of Five

【讨论】:

  • 在 GCC 中你可以打开:-Wshadow 在这种情况下应该会警告你。
  • 对于 C++11,三规则变成了五规则。对于没有明确管理资源的(除其他外)类(例如,如果 pol 变为 map&lt;int, int&gt; 而不是指向一个的指针),这将成为零规则。
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 2014-04-12
  • 2011-05-24
相关资源
最近更新 更多