初始化静态映射的正确方法是什么?我们是否需要一个静态函数来初始化它?
当前回答
你有一些非常好的答案,但对我来说,这看起来就像“当你所知道的只是一把锤子”……
为什么没有标准的方法来初始化静态映射,最简单的答案是没有好的理由去使用静态映射……
映射是为快速查找未知元素集而设计的结构。如果您事先知道元素,只需使用c数组即可。以排序的方式输入值,如果不能这样做,也可以对它们运行排序。然后,您可以通过使用stl::函数循环输入lower_bound/upper_bound来获得log(n)性能。当我之前测试这个时,它们通常比地图快至少4倍。
优势是多方面的…… -更快的性能(*4,我测量过许多类型的CPU,它总是在4左右) -调试更简单。线性布局更容易看到发生了什么。 -复制操作的琐碎实现,如果这成为必要的。 -它在运行时不分配内存,因此永远不会抛出异常。 -它是一个标准的接口,因此很容易跨DLL或语言共享。
我可以继续列举,但如果你想了解更多,为什么不看看Stroustrup关于这个主题的许多博客呢?
其他回答
这类似于PierreBdR,但没有复制映射。
#include <map>
using namespace std;
bool create_map(map<int,int> &m)
{
m[1] = 2;
m[3] = 4;
m[5] = 6;
return true;
}
static map<int,int> m;
static bool _dummy = create_map (m);
例如:
const std::map<LogLevel, const char*> g_log_levels_dsc =
{
{ LogLevel::Disabled, "[---]" },
{ LogLevel::Info, "[inf]" },
{ LogLevel::Warning, "[wrn]" },
{ LogLevel::Error, "[err]" },
{ LogLevel::Debug, "[dbg]" }
};
如果map是一个类的数据成员,你可以通过以下方式直接在header中初始化它(自c++ 17开始):
// Example
template<>
class StringConverter<CacheMode> final
{
public:
static auto convert(CacheMode mode) -> const std::string&
{
// validate...
return s_modes.at(mode);
}
private:
static inline const std::map<CacheMode, std::string> s_modes =
{
{ CacheMode::All, "All" },
{ CacheMode::Selective, "Selective" },
{ CacheMode::None, "None" }
// etc
};
};
下面是使用2元素数据构造函数的另一种方式。不需要函数来初始化它。没有第三方代码(Boost),没有静态函数或对象,没有技巧,只有简单的c++:
#include <map>
#include <string>
typedef std::map<std::string, int> MyMap;
const MyMap::value_type rawData[] = {
MyMap::value_type("hello", 42),
MyMap::value_type("world", 88),
};
const int numElems = sizeof rawData / sizeof rawData[0];
MyMap myMap(rawData, rawData + numElems);
既然我写了这个答案,c++ 11就过时了。你现在可以使用新的初始化列表功能直接初始化STL容器:
const MyMap myMap = { {"hello", 42}, {"world", 88} };
最好的方法是使用函数:
#include <map>
using namespace std;
map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
map<int,int> m = create_map();
使用c++ 11:
#include <map>
using namespace std;
map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
使用Boost。分配:
#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;
map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?
- 为什么std::map被实现为红黑树?