考虑问题末尾的示例,每次GetName()
调用函数时都会创建地图对象吗?
或者创建将被优化并创建为一些查找表?
#include <iostream>
#include <sstream>
#include <map>
#include <string>
#include <boost/assign/list_of.hpp>
enum abc
{
A = 1,
B,
C
};
std::string GetName( const abc v )
{
const std::map< abc, std::string > values =
boost::assign::map_list_of( A, "A" )( B, "B" )( C, "C" );
std::map< abc, std::string >::const_iterator it = values.find( v );
if ( values.end() == it )
{
std::stringstream ss;
ss << "invalid value (" << static_cast< int >( v ) << ")";
return ss.str();
}
return it->second;
}
int main()
{
const abc a = A;
const abc b = B;
const abc c = C;
const abc d = static_cast< abc >( 123 );
std::cout<<"a="<<GetName(a)<<std::endl;
std::cout<<"b="<<GetName(b)<<std::endl;
std::cout<<"c="<<GetName(c)<<std::endl;
std::cout<<"d="<<GetName(d)<<std::endl;
}