c++ - 以结构为键的 std::map

标签 c++ visual-studio-2015 std

我尝试使用 std::map 并将键作为 Struct,但找不到键。 这里有什么问题? Find 没有找到但是 insert 不会改变 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() 没有按预期工作。

最佳答案

你的 opeator<不会正确排序您的元素,因为如果 Typ 则返回 true更小或者如果Length更小。

#include <tuple>

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

关于c++ - 以结构为键的 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44736803/

相关文章:

c++ - 在 DX11 应用程序中使用 DirectXHelper.h 会导致 Visual Studio 2015 中出现 'namespace/class not found' 错误

c++ - 将 std::normal_distribution 绑定(bind)到 std::function 以存储在 std::vector 中

c++ - 在使用 std::set 时重载运算符 <

c++ - 友元函数看不到私有(private)成员变量

c++ - CMake 生成没有 glob 的源文件列表

c++ - 警告 : control reaches end of non-void function in recursive function

c++ - 为什么 List 类必须包含一个 Node 结构作为私有(private)成员 C++

visual-studio-2015 - Visual Studio 2015警告未找到System.Runtime(但VS2013很好)

c# - 如何从 VS2015 定位 Mono 框架?

c++ - 与指针 vector 一起使用的对象 vector