【问题标题】:How to convert map<int, string> from c++11 to c++98?如何将 map<int, string> 从 c++11 转换为 c++98?
【发布时间】:2020-04-11 21:14:10
【问题描述】:

我在 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”没有命名类型|

请帮忙。

【问题讨论】:

  • 向地图中插入内容的代码必须在函数内部。它不能处于声明级别。 C++ 不能以这种方式工作。
  • gives me the error 'finalStates' does not name a type 请发布确切的错误消息。您是否尝试在文件范围内调用函数 finalStates.insert(

标签: c++ c++98


【解决方案1】:

错误“finalStates”没有命名类型

在 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();

【讨论】:

  • 我很难不输入auto
  • 这也是我初始化此类地图的首选方式。也可以考虑将此函数设为静态并将其放入匿名命名空间中,以便仅在当前模块内调用它。
  • 您可以简单地使用operator[] 插入默认构造的字符串并分配给它,而不是输入配对类型:finalStates[0]="eroare lexicala"; finalStates[1]="identificator";。它足够便宜(而且比创建一个临时的std::string 并复制它便宜)。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

    #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&lt;int, string&gt;派生一个类并提供一个构造函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多