gpt4 book ai didi

c++ - 使用模板参数初始化 STL 类

转载 作者:行者123 更新时间:2023-11-28 07:58:03 33 4
gpt4 key购买 nike

我正在尝试使用模板参数声明一个 STL 映射,如下所示:(假设 T 为类型名称,如下所示:template <class T>)

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

它编译得很好。现在在我的 cpp 文件中,当我想插入 map 时,我无法插入。我在智能感知上获得的唯一方法是“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
};

最佳答案

将键值对插入 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 生成要存储在 map 中的 t 的值。)

关于c++ - 使用模板参数初始化 STL 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12233066/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com