在struct中插入C ++ [英] C++ insert in struct
本文介绍了在struct中插入C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下:
struct d
{
char name[5];
};
vector<d> my_d;
my_d.resize(3);
strcpy(my_d[0].name, "mike");
strcpy(my_d[1].name, "joe");
//how to insert "anna" between "mike" and "joe"
my_d.insert(my_d.begin()+1, "anna");//doesn't work???
我试图在元素之间插入一个元素,如上所示。但是编译器拒绝编译,没有重载函数的实例将协议列表。
。
I am trying to insert an element between the elements, as show above. But the compiler refuses to compile, No instance of overloaded function maches the agreement list.
.
推荐答案
没有从字符串文字( const char *
)到 d
类型的隐式转换。您必须创建新的 d
结构,将字符串复制到其中,然后将其添加到 my_d
:
There is no implicit conversion from a string literal (const char*
) into a d
type. You'll have to make the new d
struct, copy the string into it, then add it to my_d
:
d newItem;
strcpy(newItem.name, "anna");
my_d.insert(my_d.begin()+1, newItem);
如果你想隐式类型转换,你需要在 d
这样的结构:
If you want implicit type conversion, you need to provide a constructor on the d
struct like this:
struct d {
char name[5];
d(const char* name_) {
strcpy(name, name_);
}
}
这篇关于在struct中插入C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文