[英]Compilation error when returning an std::map of implicitly non-copyable structs on new versions of gcc
[英]How can I solve a compilation error when declaring a map of structs?
我在使用struct
s map
时遇到以下错误:
Error: invalid types 'int[unsigned int]' for array subscript
。
typedef struct {
std::string s;
}re;
re r;
std::map<unsigned int, r> var;
int main(){
struct re{
string s;
}re;
re.s="hello";
var[10]=re;}
如果我将r
更改为map
的声明中的re
,则将收到错误消息:
error: no match for 'operator=' in var.std::map<_Key, _Tp, _Compare, _Alloc>::operator[] [with _Key = unsigned int, _Tp = re, _Compare = std::less<unsigned int>, _Alloc = std::allocator<std::pair<const unsigned int, re> >, std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = re, std::map<_Key, _Tp, _Compare, _Alloc>::key_type = unsigned int]((*(const key_type*)(& o) = re'
地图需要为mapped_type一个类型,你给它re
实例r
你需要
std::map<unsigned int, re> var;
您的代码可以进一步简化:
struct re {
std::string s;
};
int main()
{
re r;
std::map<unsigned int, re> var;
r.s="hello";
var[10]=r;
}
r
是re
类型的实例 ,它是您定义的struct
的类型别名。 因此,您应该更改此设置:
std::map<unsigned int, r> var;
进入他的:
std::map<unsigned int, re> var;
// ^^
还要注意,在main()
过程中,您很可能只想创建一个reins实例时就在re
定义它的结构:
int main() {
re r;
r.s="hello";
var[10]=r;
}
因此,将所有内容放在一起:
#include <string>
#include <map>
// Avoid this old C style of defining structs. Prefer the
// C++ style I am showing below...
/*
typedef struct {
std::string s;
} re;
*/
struct re
{
std::string s;
};
int main() {
std::map<unsigned int, re> var;
re r;
r.s="hello";
var[10]=r;
}
首先,你可以说
struct re { std::string s; };
在C ++中。 typedef struct {...} name;
是一个C主义。
在地图中,您必须提供类型而不是变量
std::map<unsigned int, re> var;
您在main()
函数中遇到的错误是因为您尝试将main()::struct re
类型不同的变量分配给map元素10
,其类型为typedef struct { ... } re
。
总而言之,main中的struct re
与全局范围中的typedef ... re
。
请更换
std::map<unsigned int, r> var;
进入
std::map<unsigned int, re> var;
您定义某种类型的地图,在<>
,将要映射的类型传递到“地图”(定义它们之间的映射)。
这是所有代码段:
#include <map>
typedef struct {
std::string s;
}re;
re r;
std::map<unsigned int, re> var;
int f(int argc, char** argv) {
re res;
res.s="hello";
var[10]=res;
//and if you want that global variable
r.s="global variable";
var[1]=r;
return ERROR_SUCCESS;
}
内联注释描述了如何修复代码。
#include <string>
#include <map>
//typedef struct { // This is from C. Use the C++ way...
struct re_type {
std::string s;
//} re; // See above
};
// re r; // You do not need a global instance
// std::map<unsigned int, r> var; // `r` was an instance.
// The map declaration needs a type:
std::map<unsigned int, re_type> var; // Note: This is global and should probably be
// moved into main()
int main(){
// struct re{ // No need to redeclare the struct here
// string s;
// }re;
re_type re; // Create a local instance
re.s="hello";
var[10]=re;
}
re
, r
, s
和var
似乎不是描述性标识符。 使用有意义的标识符将使您的代码更易于阅读和维护,甚至可以帮助您理解出现的编译错误。
typedef struct {
std::string s;
} re;
然后再:
std::map<unsigned int, r> var;
没事 模板需要类型,但是您要给它一个变量。 更改为
std::map<unsigned int, re> var;
它将正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.