【问题标题】:Initializing stl classes with template parameters使用模板参数初始化 stl 类
【发布时间】:2012-09-02 02:51:15
【问题描述】:

我正在尝试使用如下模板参数声明一个 stl 映射: (假设 T 为 typename 像这样:template <class T>

map<T, T> m;(在.h文件中)

它编译得很好。现在在我的 cpp 文件中,当我想插入地图时,我不能。我在智能感知上获得的唯一方法是“at”和“swap”方法。

有什么想法吗?请问有人吗?

提前致谢。

这里是示例代码:

#pragma once

#include <iostream>
#include <map>

using namespace std;

template <class T> 

class MySample  
{  
map<T, T> myMap;
//other details omitted

public:

//constructor 
MySample(T t)
{
    //here I am not able to use any map methods. 
    //for example i want to insert some elements into the map
    //but the only methods I can see with Visual Studio intellisense
    //are the "at" and "swap" and two other operators
    //Why???
    myMap.  
}

//destructor
~MySample(void)
{

}
//other details omitted
};

【问题讨论】:

  • 发布一些代码...我们不在您的屏幕前,所以如果您想要答案,您可能希望帮助我们了解您的问题...
  • 我添加了一些示例代码。如果我做错了,请告诉我。
  • 如果您只是按照我的回答中描述的行键入代码,那么代码是否可以编译?也许这只是你的 IDE 的自动建议功能的问题。
  • 解析 C++ 并正确解析所有标识符的名称是异常复杂的。编写一个正确的编译器已经够难了,而且 IntelliSense 必须比完全编译更快地生成一些合理的东西,即使代码处于语法错误状态也是如此。令人惊讶的是它的效果和它一样好,但不要依赖它!这只是一种“尽力而为”的启发式方法。

标签: c++ stl map initialization std


【解决方案1】:

将键值对插入std::map 的常用方法是索引运算符语法和insert 函数。为了示例,我将假设 std::string 用于键,int 用于值:

#include <map>
#include <string>

std::map<std::string,int> m;
m["hello"] = 4;  // insert a pair ("hello",4)
m.insert(std::make_pair("hello",4)); // alternative way of doing the same

如果你可以使用 C++11,你可以使用新的统一初始化语法来代替 make_pair 调用:

m.insert({"hello",4});

而且,正如 cmets 中所说,有

m.emplace("hello",4);

在 C++11 中,它就地构造新的键值对,而不是在映射之外构造它并复制它。


我应该补充一点,因为您的问题实际上是关于 初始化,而不是插入新元素,并且鉴于您确实在 MyClass 的构造函数中执行此操作,您应该真正做什么(在C++11) 是这样的:

MySample(T t)
 : myMap { { t,val(t) } }
{}

(这里我假设有一些函数 val 生成要存储在地图中的 t 的值。)

【讨论】:

  • 在C++11中,也可以使用emplace
  • 我添加了一些示例代码。如果我做错了,请告诉我。
  • @MarceloCantos 所以你确实可以!谢谢。 (不过,我的 STL 的 GCC 4.7.0 实现似乎没有定义 std::map&lt;&gt;::emplace。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多