简体   繁体   English

使用模板参数初始化STL类

[英]Initializing stl classes with template parameters

I am trying to do declare a stl map with template parameters like so: ( assume T as typename like so : template <class T> ) 我试图用这样的模板参数声明一个stl映射:(假定T为这样的类型名: template <class T>

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

It compiles fine. 它编译良好。 now in my cpp file, when I want to insert into the map, i am not able to. 现在在我的cpp文件中,当我想插入地图时,我无法。 The only methods i get on intellisense are "at" and "swap" methods. 我在智能感知上获得的唯一方法是“ at”和“ swap”方法。

Any ideas? 有任何想法吗? Anyone please? 有人吗

Thanks in advance. 提前致谢。

here is sample code: 这是示例代码:

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

The usual ways to insert key-value pairs into a std::map are the index-operator syntax as well as the insert function. 将键值对插入到std::map中的常用方法是index-operator语法以及insert函数。 I'll assume std::string for keys and int for values for the sake of the example: 为了示例,我假设键为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

If you can use C++11, you may use the new uniform initialization syntax instead of the make_pair call: 如果可以使用C ++ 11,则可以使用新的统一初始化语法而不是make_pair调用:

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

And, as said in the comments, there is 而且,正如评论中所说,

m.emplace("hello",4);

in C++11, which constructs the new key-value pair in-place, rather than constructing it outside the map and copying it in. 在C ++ 11中,它就地构造了新的键-值对,而不是在地图外部构造并复制到其中。


I should add that since your question is actually about initialization , rather than inserting fresh elements, and given that indeed you do this in the constructor of MyClass , what you should really do (in C++11) is this: 我应该补充一点,因为您的问题实际上是关于初始化的 ,而不是插入新鲜的元素,并且考虑到确实在MyClass的构造函数中执行了此操作,所以您真正应该做的(在C ++ 11中)是:

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

(Here I assume there is some function val which generates the value to store for t in the map.) (这里我假设有一些函数val ,该函数会生成要在地图上存储t的值。)

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

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