繁体   English   中英

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

[英]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'没有命名类型|

请帮忙。

错误“finalStates”没有命名类型

在 C++ 中,不能在外部(全局)scope 中有语句。 您必须将它们放入一些 function 中。 C++11 代码没有声明,只有定义。

C++98 替代方案(如果 map 应该是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();

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

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

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

然后声明 map

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

其他人已经正确地涵盖了它。 我唯一想补充的是,如果您希望在全局 object 构造时初始化 map,您可能希望将初始化代码放入全局 object 构造函数中:

#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;

这样,map 将在main()启动时获得其值。 要么,要么从map<int, string>派生class 并提供构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM