【问题标题】:How to create a function with return type map<>?如何创建返回类型为 map<> 的函数?
【发布时间】:2011-02-27 19:49:28
【问题描述】:

相当简单的问题。我有一张地图,我希望通过调用这样的函数来初始化:

map&lt;string, int&gt; myMap;

myMap = initMap( &amp;myMap );

map<string, int> initMap( map<string, int> *theMap )
{
    /* do stuff... */

但是,编译器在抱怨。有什么办法解决这个问题?

编辑 1:

对不起,我搞砸了。代码用*theMap 正确编写,但是当我发布问题时,我没有注意到我省略了*。所以回答评论,我得到的错误信息是:

1&gt;Roman_Numerals.cpp(21): error C2143: syntax error : missing ';' before '&lt;'

扔在哪里

map&lt;char, int&gt; initMap( map&lt;char, int&gt; *numerals );

使用 VC++ 2010 Express 定义函数时再次出现同样的错误。

【问题讨论】:

  • 编译器告诉你的错误信息是什么?

标签: c++ function map return


【解决方案1】:

要么做:

map<string, int> myMap;
initMap( myMap );

void initMap( map<string, int>& theMap )
{
    /* do stuff in theMap */
}

或者做:

map<string, int> myMap;
myMap = initMap(  );

map<string, int> initMap()
{
    map<string, int> theMap;
    /* do stuff in theMap */
    return theMap;
}

即让函数初始化你给它的地图,或者获取函数给你的地图。你正在做这两个(也没有return 声明!)

我会选择第一个选项。

【讨论】:

    【解决方案2】:

    这可能是在抱怨,因为您传递了地图的地址,但您的函数按值接受了地图。

    你可能想要更多这样的东西:

    void initMap(map<string, int>& theMap)
    {
        /* do stuff...*/
    }
    

    【讨论】:

    • 感谢您的回答,但实际上我错误地重写了我的代码。它包含地图 *theMap,我只是在我在这里编写的代码中留下了指针>
    【解决方案3】:

    规范的解决方案只是

    std::map<std::string, int> initMap();
    // ...
    std::map<std::string, int> myMap = initMap();
    

    为什么要尝试使用输入参数作为返回值?表现?现代编译器不在乎。实际上,不构建空地图会稍微快一些。

    【讨论】:

      【解决方案4】:

      您应该接受一个指针,或者最好是一个对地图的引用。为方便起见,您还可以返回参考:

      map<string, int>& initMap( map<string, int>& theMap )
      ...
      // Call initMap
      map<string, int> my_map;
      initMap(my_map);
      

      【讨论】:

        【解决方案5】:

        为什么不做 void initMap(map& theMap),而不是制作这么多的地图副本?

        【讨论】:

          【解决方案6】:

          &amp;myMap 是指向映射对象的指针,而参数theMap 是映射对象。

          两种解决方案:

          myMap = initMap( &amp;myMap ); 更改为myMap = initMap( myMap );

          map&lt;string, int&gt; initMap( map&lt;string, int&gt; theMap ) 更改为map&lt;string, int&gt; initMap( map&lt;string, int&gt; * theMap )

          【讨论】:

            【解决方案7】:

            比赛有点晚了,但是: 我会从错误消息中猜出你错过了

            #include <map>
            

            在代码的顶部。所以编译器不知道 map 应该是一个模板,因此它会被后面的尖括号弄糊涂。

            【讨论】:

              【解决方案8】:
               void initMap(map<String,int> &Map)
               {
                 //Do something
               }
              

              【讨论】:

              • 您能否扩展此答案,添加解释是什么/为什么有效?
              • 您将 map 的引用传递给 init 函数。
              • 返回值也不对应于 OP 所要求的 map&lt;K,T&gt;。请不要发布乱七八糟的东西。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-05-09
              • 2021-06-27
              相关资源
              最近更新 更多