结构初始化向量 [英] Vector of structs initialization
本文介绍了结构初始化向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何使用 push_back
方法向我的结构向量添加值
I want know how I can add values to my vector of structs using the push_back
method
struct subject
{
string name;
int marks;
int credits;
};
vector<subject> sub;
那么现在如何向其中添加元素?
So now how can I add elements to it?
我具有初始化字符串名称(对象名称)的功能
I have function that initializes string name(subject name to it)
void setName(string s1, string s2, ...... string s6)
{
// how can i set name too sub[0].name= "english", sub[1].name = "math" etc
sub[0].name = s1 // gives segmentation fault; so how do I use push_back method?
sub.name.push_back(s1);
sub.name.push_back(s2);
sub.name.push_back(s3);
sub.name.push_back(s4);
sub.name.push_back(s6);
}
函数调用
setName("english", "math", "physics" ... "economics");
推荐答案
创建矢量,push_back元素,然后对其进行如下修改:
Create vector, push_back element, then modify it as so:
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
}
您无法使用[#]访问向量,直到向量中位于该索引处的元素为止.此示例填充[#],然后对其进行修改.
You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.
这篇关于结构初始化向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文