以结构为键的 std::map [英] std::map with struct as key

查看:36
本文介绍了以结构为键的 std::map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 std::map 的键作为 Struct,但在找到键时失败.这里有什么问题?查找未找到但插入不会更改地图中的计数.....

i'm try to use a std::map with the key as Struct, but it fails on find the key. what is wrong here? Find does not find but insert will not change the count in the map.....

#pragma once
#include <map>
struct OccTestdef
{

public:
    int Typ;
    int Length;

    OccTestdef(int typ,  int length) :Typ(typ), Length(length) {};

    bool operator < (const OccTestdef& R) const
    {
        if (Typ < R.Typ)  return true;
        if (Length < R.Length) return true;
        return false;
    }

};


typedef std::map<OccTestdef, int> Testmap;
typedef std::pair<OccTestdef, int> Testpair;

class testocc
{
public:
    testocc();
    ~testocc(){}

    bool runtest();

private:
    Testmap tests;

    int addOrInsert(int left, int num, int value);

};

和 cpp:

#include "testocc.h"

testocc::testocc()
{
    tests = Testmap();
}

// Will Return the Map-Value if found or -1 if new Inserted
int testocc::addOrInsert(int left, int num, int value)
{
    int res;
    OccTestdef tn(left, num);
    auto result = tests.find(tn);
    if (result != tests.end()) {
        res = result->second;
    }
    else
    {
        tests.insert(Testpair(tn, value));
        res = -1;
    }
    return res;
}

bool testocc::runtest()
{
    int res;
    bool result;
// Fill map with 4 Entries
    tests.insert(Testpair( OccTestdef(1, 100), 1));
    tests.insert(Testpair(OccTestdef(1, 200), 2));
    tests.insert(Testpair(OccTestdef(1, 300), 3));
    tests.insert(Testpair(OccTestdef(1, 400), 4));


    result = (tests.size() == 4);
// Try to find or Insert 
     res = addOrInsert(1, 200, 2);
    //res should be 2 
    result = (res == 2);

    result = (tests.size() == 4);

    res = addOrInsert(2, 200, 20);
    // Res must be -1 because new inserted
    result = (res == -1);

    // Count is not changed
    result = (tests.size() == 5);


//These fails why?
    res = addOrInsert(2, 200, 20);
    //res should be 20 
    result = (res == 20);
    return result;
}

我不明白为什么 test.find() 没有按预期工作.

I don't understand why the test.find() is not working as expected.

推荐答案

您的 opeator< 将无法正确排序您的元素,因为如果 Typ 较小或长度较小.

Your opeator< will not order your elements properly because you return true if Typ is smaller or if Length is smaller.

#include <tuple>

bool operator < (const OccTestdef& R) const
{
    return std::tie(Typ, Length) < std::tie(R.Typ, R.Length);
}

这篇关于以结构为键的 std::map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆