C++ std::map 屏蔽排序

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

  最近在项目中用标准库中的关联性容器map,但知道map默认升序的,但在一个需求时又不想让它排序,保持元素原始位置,查了资料发现,标注库中有不排序的map,unordered_map。

用法一:

包含头文件 #include<unordered_map>

std::unordered_map<std::string,int> m; 

和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::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;
    }
}

int main()
{
    test();
    getchar();
    return 0;
}

运行结果:

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

猜你喜欢

转载自www.cnblogs.com/chechen/p/12075512.html