如何将 map<int, string> 从 c++11 转换为 c++98?

How to convert map<int, string> from c++11 to c++98?

我在 C++11 中有这段代码:

#include <string>
#include <map>
using namespace std;

map<int, string> finalStates =
{
    { 0, "eroare lexicala" },
    { 1,  "identificator" } 
};

我尝试将其转换为 C++98,如:

#include <string>
#include <map>

std::map<int, std::string> finalStates;

finalStates.insert( std::pair<int, std:string> (0, "eroare lexicala"));
finalStates.insert( std::pair<int, std:string> (1,  "identificator"));

这给我错误 'finalStates' does not name a type|

拜托,帮忙。

error 'finalStates' does not name a type

在 C++ 中,您不能在外部(全局)作用域中拥有语句。您必须将它们放在某个函数中。 C++11代码没有语句,只有定义。

C++98 替代方案(如果地图应该是 const 特别有用):

#include <string>
#include <map>

std::map<int, std::string> construct_final_states()
{
    std::map<int, std::string> finalStates;
    finalStates.insert( std::pair<int, std::string> (0, "eroare lexicala"));
    finalStates.insert( std::pair<int, std::string> (1,  "identificator"));
    return finalStates;
}

std::map<int, std::string> finalStates = construct_final_states();

在任何函数之外,您只能使用声明。

例如,您可以声明一个辅助数组,例如

const std::pair<int, std::string> a[] = 
{
    std::pair<int, std::string>( 0, "eroare lexicala" ),
    std::pair<int, std::string>( 1, "identificator" )
};

然后声明地图

std::map<int, std::string> finalStates( a, a + sizeof( a ) / sizeof( *a ) );

其他人已经正确地覆盖了它。我唯一想补充的是,如果你想在全局对象构造时初始化你的地图,你可能想将初始化代码放入全局对象构造函数中:

#include <string>
#include <map>

std::map<int, std::string> finalStates;

class finalStates_init
{
public:
    finalStates_init()
    {
        finalStates.insert( std::pair<int, std:string> (0, "eroare lexicala"));
        finalStates.insert( std::pair<int, std:string> (1,  "identificator"));
    }
} the_finalStates_init;

这样,地图将在 main() 开始时具有其值。或者 map<int, string> 派生 一个 class 并提供一个构造函数。