如何正确初始化静态映射?我们需要一个静态函数来初始化它吗?
#include <map>
using namespace std;
map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
使用Boost.Assign:
#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');
最好的方法是使用函数:
#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();
extern
声明但尚未遇到实际的变量定义,那么在“main”函数运行之前的构造期间,extern
变量将不会具有其正确的值。请注意,此处指的是变量的实际定义,而非仅仅是声明。 - boboboboconst map<int,int> m = create_map()
(从而可以在类的初始化列表中初始化常量成员:struct MyClass {const map<int, int> m; MyClass(); }; MyClass::MyClass() : m(create_map())
)。 - ribamar制作类似于boost的东西并不是一个复杂的问题。下面是一个仅包含三个函数(包括构造函数)的类,用来模拟几乎与boost相同的功能。
template <typename T, typename U>
class create_map
{
private:
std::map<T, U> m_map;
public:
create_map(const T& key, const U& val)
{
m_map[key] = val;
}
create_map<T, U>& operator()(const T& key, const U& val)
{
m_map[key] = val;
return *this;
}
operator std::map<T, U>()
{
return m_map;
}
};
用法:
std::map mymap = create_map<int, int>(1,2)(3,4)(5,6);
上述代码最适合用于全局变量或类的静态成员的初始化,当您不知道第一次使用时间但需要确保其值在其中可用时。
如果您需要向现有的std::map插入元素...这里还有另一个类可以使用。
template <typename MapType>
class map_add_values {
private:
MapType mMap;
public:
typedef typename MapType::key_type KeyType;
typedef typename MapType::mapped_type MappedType;
map_add_values(const KeyType& key, const MappedType& val)
{
mMap[key] = val;
}
map_add_values& operator()(const KeyType& key, const MappedType& val) {
mMap[key] = val;
return *this;
}
void to (MapType& map) {
map.insert(mMap.begin(), mMap.end());
}
};
使用方法:
typedef std::map<int, int> Int2IntMap;
Int2IntMap testMap;
map_add_values<Int2IntMap>(1,2)(3,4)(5,6).to(testMap);
map_add_values
类是我最初建议的解决方案,但在GCC 4.5+上会失败。请查看上面的代码以了解如何向现有映射中添加值。
template<typename T, typename U>
class map_add_values
{
private:
std::map<T,U>& m_map;
public:
map_add_values(std::map<T, U>& _map):m_map(_map){}
map_add_values& operator()(const T& _key, const U& _val)
{
m_map[key] = val;
return *this;
}
};
用法:
std::map<int, int> my_map; // 稍后在代码中的某个地方 map_add_values<int,int>(my_map)(1,2)(3,4)(5,6);
注意: 我之前使用了operator []
添加实际值。正如dalle所评论的那样,这是不可能的。
##################### 过时部分的结束 #####################
operator[]
只接受一个参数。 - dalleerror: conflicting declaration ‘map_add_values<int, int> my_map’
error: ‘my_map’ has a previous declaration as ‘std::map<int, int> my_map’
- Martin Wang这里有另一种方法,它使用了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} };
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是一个类的数据成员,你可以通过以下方式直接在头文件中初始化它(自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
};
};
std::array
。 - prehistoricpenguinstd::array
比使用map
查找更快。 - prehistoricpenguin我会将地图放在一个静态对象中,并将地图初始化代码放在该对象的构造函数中。这样,您可以确保在执行初始化代码之前地图已经被创建。
我只想分享一个纯C++ 98的解决方法:
#include <map>
std::map<std::string, std::string> aka;
struct akaInit
{
akaInit()
{
aka[ "George" ] = "John";
aka[ "Joe" ] = "Al";
aka[ "Phil" ] = "Sue";
aka[ "Smitty" ] = "Yando";
}
} AkaInit;
您可以尝试:
std::map <int, int> mymap =
{
std::pair <int, int> (1, 1),
std::pair <int, int> (2, 2),
std::pair <int, int> (2, 2)
};
{1, 2}
代替std::pair<int, int>(1, 2)
。 - Ferruccio如果您被困在使用C++98且不想使用boost的情况下,这里提供了我在需要初始化静态映射时使用的解决方案:
typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] =
{
elemPair_t( 1, 'a'),
elemPair_t( 3, 'b' ),
elemPair_t( 5, 'c' ),
elemPair_t( 7, 'd' )
};
const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );
#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);