map 构造函数如何以 class 比较的形式使用?

How can map cosntructor can be use in the form of class compare?

当我在 cplusplus.com 阅读地图容器的参考资料时,我发现有 5 种使用其构造函数的方法。我了解了如何使用空容器构造函数、范围构造函数和复制构造函数。 但是移动构造函数和初始化列表构造函数呢?

这是一个使用地图构造器的例子。第四个和第五个是怎么构造的,它们的元素是什么

// constructing maps
#include <iostream>
#include <map>

bool fncomp (char lhs, char rhs) {return lhs<rhs;}

struct classcomp {
   bool operator() (const char& lhs, const char& rhs) const
   {return lhs<rhs;}
};

int main ()
{
   std::map<char,int> first;

   first['a']=10;
   first['b']=30;
   first['c']=50;
   first['d']=70;

   std::map<char,int> second (first.begin(),first.end());

   std::map<char,int> third (second);

   std::map<char,int,classcomp> fourth;                 // class as Compare

   bool(*fn_pt)(char,char) = fncomp;
   std::map<char,int,bool(*)(char,char)> fifth (fn_pt); // function pointer as Compare

   return 0;
}

第四个构造函数重载是移动构造函数。移动语义基本上是一种从即将被销毁的临时对象中窃取资源的方法。

如果您编写了一个 return 编辑 std::map 的函数,并试图通过 return 值初始化一个新函数,如:

std:: map <char, int> f ();
map <char, int> new_map (f());

new_map 将从 f 的结果 构造 移动。

您可以找到 "rvalue references" 和 "move semantics" here 的绝妙解释。

initializer-list 构造函数使用新的大括号初始化语法,可能如下所示:

std:: map <char, char> TranslationTable {{'G', 'C'}, {'C', 'G'}, 
                                         {'T', 'A'}, {'A', 'T'}};