Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of structs initialization

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);  } 

Function call

setName("english", "math", "physics" ... "economics"); 
like image 863
SRN Avatar asked Nov 09 '11 15:11

SRN


People also ask

How do you initialize a vector in a struct?

To properly initialize a structure, you should write a ctor to replace the compiler provided ctor (which generally does nothing). Something like the following (with just a few attributes): struct grupo { float transX, transY; // ...

Can you have a vector of structs?

To create a vector of structs, define the struct, with a generalized (class) name. Make the template argument of the vector of interest, the generalized name of the struct. Access each cell of the two dimensional structure with the syntax, vtr[i].


1 Answers

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.

like image 101
John Humphreys Avatar answered Oct 12 '22 14:10

John Humphreys