2012-09-02 145 views
0

我试图做一个声明STL的地图,像这样的模板参数: (假设T作为类型名,像这样:template <class T>初始化STL类与模板参数

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

它编译好。现在在我的cpp文件中,当我想插入地图时,我无法。我在intellisense上获得的唯一方法是“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 
}; 
+0

任何人都可以吗? – lat

+0

发表一些代码...我们不在你的屏幕前,所以你可能想帮助我们理解你的问题,如果你想要的答案... – Macmade

+0

我添加了一些示例代码。让我知道我所做的是错的。 – lat

回答

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

而且,作为评价所述,有

m.emplace("hello",4); 

在C++ 11,它构造新的键 - 值对就地拉特呃不是构造它的地图之外,并复制它。


我要补充一点,因为你的问题其实是关于初始化,而不是插入的新鲜元素,并考虑到你确实做到这一点在构造函数MyClass,你应该怎么做(在C++ 11)是这样的:

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

(这里我认为有一些功能val产生了t在地图存储值)。

+1

在C++ 11中,您也可以使用[emplace](http://en.cppreference.com/w/cpp/container/map/emplace)。 –

+0

我添加了一些示例代码。让我知道我所做的是错的。 – lat

+0

@MarceloCantos所以你的确可以!谢谢。 (尽管我的GCC 4.7.0 STL实现似乎没有定义'std :: map <> :: emplace')。) – jogojapan