在 C++ 中使用用户定义的类型作为映射值
Using a user-defined type as map value in c++
我是 C++ 编程的新手,在使用 std::map class 时遇到了问题。
我想将一个 int 值映射到一个自定义类型。映射应该包含实际值而不是指向它的指针!
例子:
我想这样做:map<int,Type>
而不是这样:map<int,Type*>
.
我试过的是:
map<int,Type> myMap;
myMap.insert(make_pair(keyVal,Type(intVal,intVal,intVal))); //Type takes 3 int-values for construction.
myMap[intVal].useMemberFunction();
错误信息是
error: no matching function for call to ‘Type::Type()’ second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
Type
是我的用户自定义类型。是否可以像这样实例化一个对象,还是我必须以某种方式使用 new
运算符?
我怎样才能使这个工作?
我在网上搜索了它,但我发现的只是使用用户定义的类型作为键,这不是我想要做的。
Is it possible to instantiate an object like this
是的,是的。
or do i have to use the new operator in some way?
不,你不知道。
How can i make this work?
这已经有效,假设您定义了示例中缺少的变量和类型:
#include <map>
#include <utility>
using std::map;
using std::make_pair;
struct Type {
Type(int,int,int){}
Type(){}
void useMemberFunction(){}
};
int main() {
int keyVal = 0, intVal = 0;
map<int,Type> myMap;
myMap.insert(make_pair(keyVal,Type(intVal,intVal,intVal))); //Type takes 3 int-values for construction.
myMap[intVal].useMemberFunction();
}
不过请注意:根据文档,std::map::operator[]
要求值类型是默认可构造的。如果类型不是默认可构造的,则不能使用下标运算符。您可以改用 std::map::at
或 std::map::find
。
我是 C++ 编程的新手,在使用 std::map class 时遇到了问题。
我想将一个 int 值映射到一个自定义类型。映射应该包含实际值而不是指向它的指针!
例子:
我想这样做:map<int,Type>
而不是这样:map<int,Type*>
.
我试过的是:
map<int,Type> myMap;
myMap.insert(make_pair(keyVal,Type(intVal,intVal,intVal))); //Type takes 3 int-values for construction.
myMap[intVal].useMemberFunction();
错误信息是
error: no matching function for call to ‘Type::Type()’ second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
Type
是我的用户自定义类型。是否可以像这样实例化一个对象,还是我必须以某种方式使用 new
运算符?
我怎样才能使这个工作?
我在网上搜索了它,但我发现的只是使用用户定义的类型作为键,这不是我想要做的。
Is it possible to instantiate an object like this
是的,是的。
or do i have to use the new operator in some way?
不,你不知道。
How can i make this work?
这已经有效,假设您定义了示例中缺少的变量和类型:
#include <map>
#include <utility>
using std::map;
using std::make_pair;
struct Type {
Type(int,int,int){}
Type(){}
void useMemberFunction(){}
};
int main() {
int keyVal = 0, intVal = 0;
map<int,Type> myMap;
myMap.insert(make_pair(keyVal,Type(intVal,intVal,intVal))); //Type takes 3 int-values for construction.
myMap[intVal].useMemberFunction();
}
不过请注意:根据文档,std::map::operator[]
要求值类型是默认可构造的。如果类型不是默认可构造的,则不能使用下标运算符。您可以改用 std::map::at
或 std::map::find
。