• C++ std::map 屏蔽排序(没法使用find函数)


    转载:https://blog.csdn.net/sendinn/article/details/96286849

      最近在项目中用标准库中的关联性容器map,但知道map默认升序的,但在一个需求时又不想让它排序,保持元素原始位置。原先查了资料发现,标注库中有不排序的map,可以重写map的第三个比较函数,但实际使用中发现,用了自定义的比较函数,map的find函数没法用。

    unordered_map:

    包含头文件 #include<unordered_map>

    关联性:std::unorederd_map 是一个关联容器,其中的元素根据键来引用,而不是根据索引来引用。

    无序性:在内部,std::unordered_map中的元素不会根据其键值或映射值按任何特定顺序排序,而是根据其哈希值组织到桶中,以允许通过键值直接快速访问各个元素(常量的平均时间复杂度)。

    唯一性:std::unorederd_map中的元素的键是唯一的。

    void testUnordermap()
    {
        std::unordered_map<std::string, int> unm;
        unm["d"] = 1;
        unm["c"] = 2;
        unm["b"] = 3;
        unm["a"] = 4;
        unm["a"] = 5;
    
        std::unordered_map<std::string, int>::iterator iter1 = unm.begin();
        for (; iter1 != unm.end(); iter1++)
        {
            std::cout << "unordered_map:   " << iter1->first.c_str() << std::endl;
        }
    
        unm["j"] = 1;
    }

    运行结果:

    map:

    在网上查资料说,map容器有4个参数,其中影响自动排序的是第三个参数,只要保证为true即可。

    上给出的多是直接返回true或是if (lhs == rhs) return false; return true;(加了相同的key则默认处理返回false的条件)

    但是其实map如果想第三个参数返回true需要经过两次比较,如果第一次返回true那么会把左右参数对调再判断一次,这一次则要返回false,才能无序排列,所以要多加些条件。

    #include <iostream>
    #include <unordered_map>
    #include <map>
    
    template<class T>
    struct DisableCompare : public std::binary_function<T,T,bool>
    {
        bool operator()(T lhs,T rhs)const
        {
            static bool disblecompare = false;
            if (lhs == rhs)
            {
                return false;
            }
            if (disblecompare)
            {
                disblecompare = false;
                return false;
            }
            else
            {
                disblecompare = true;
                return true;
            }
        }
    };
    
    void test()
    {
        std::map<std::string, int, DisableCompare<std::string>> m;
        m["d"] = 1;
        m["c"] = 2;
        m["b"] = 3;
        m["a"] = 4;
        m["a"] = 5;
    
        std::map<std::string, int>::iterator iter = m.begin();
        for (; iter != m.end();iter++)
        {
            std::cout << "map:   " << iter->first.c_str() << std::endl;
        }
    std::map<std::string, int>::iterator iter1 = m.find("d");
    } int main() { test(); getchar(); return 0; }

    如果只想不排序,不用find的话,可以采用这种方法,但实际需求,一般都会使用map的find函数,所以在此还需要想其他办法。

     也许不是这种特殊需求,我们只知道用map,并利用它的默认排序,知识的积累真是一点一滴的,没有捷径。

  • 相关阅读:
    Oracle DBA手记3:数据库性能优化与内部原理解析
    产品部和业务部门的利益之争
    利用dir函数查询各个数据类型的方法
    Python自动单元测试框架
    十一长假归来
    我心爱的TT被我擦到了,伤心!
    150首现代最流行的歌曲连放
    Increase bugzilla attachment size
    Python中的搜索路径
    抛出异常
  • 原文地址:https://www.cnblogs.com/chechen/p/12075512.html
Copyright © 2020-2023  润新知