当覆盖地图中的复杂对象键时,旧对象将被删除(C ++)

时间:2018-07-20 18:52:55

标签: c++ memory-management stdmap

我有一个<MyObject, int>映射来计算每个实例的出现次数。用相等的myObject2覆盖键myObject1后,会删除myObject1并恢复分配给myObject1的内存吗?

例如,我有一个文本文件,其中包括人的姓名,性别,年龄,身高。假设我只想计算多少对唯一的(姓名,性别)对。因此,我创建了我的Person(字符串名称,int性别)对象,并将其添加到std :: map(假设我必须使用map而不是set)

std::map<Person, int> myMapCounter;
//for each line
  Person newperson(name, gender);
  myMapCounter[newperson] = 1 ;// just a dummy value 
//end for 

int number = myMapCounter.size();

在创建与上一行中的旧对象相等的新Person对象时,将myMapCounter[newperson] = 1删除旧对象(恢复内存,因此该“ person”只有1块内存),或者“旧”对象仍将存在于内存中吗?

1 个答案:

答案 0 :(得分:1)

好吧,当实现operator <函数时,它对我有用。 想要添加时,std::map中的键要与其他键一起查询<

要向地图中添加Person结构/类时,是否与其他人一起查询。

尝试这样的代码以查看实际发生的情况

#include <map>
#include <iostream>
#include <string>

class Person {
private:
    std::string name;
    std::string gender;
public:
    Person(std::string name, std::string gender): name(name), gender(gender) {}
    Person(const Person &person): name(person.name), gender(person.gender) {}
    inline std::string getName() const { return name; }
    inline std::string getGender() const { return gender; }
    friend bool operator <(const Person &first, const Person &other);
};

inline bool operator <(const Person &first, const Person &other)
{
    std::cout << "Comparing " << first.name << " with " << other.name << "\n";
    if (first.name == other.name) {
        return first.gender < other.gender;
    } else {
        return first.name < other.name;
    }
}

int main() {
    std::map<Person, int> map;
    map[Person("One", "male")] = 1;
    map[Person("Two", "male")] = 4;
    map[Person("A", "male")] = 3;
    std::cout << "Ending adding\n";
    std::cout << map[Person("One", "male")];
}

您会看到类似的东西

Comparing Two with One
Comparing One with Two
Comparing A with One
Ending adding
Comparing One with One
Comparing One with One