Thursday, July 30, 2009

Can a vector be made up of structs, in C++?

Why doesn't this code work? I'm using G++ compiler.








#include%26lt;iostream%26gt;


#include%26lt;vector%26gt;





int main(){





struct date{





int day;


int month;


int year;


};








std::vector%26lt;date%26gt; x;











return 0;


};





Would there be away to make a vector with the type one of your own? Thanks

Can a vector be made up of structs, in C++?
This works but haven't been able to get it to work with the struct inside main. There is some kind of namespace problem where vector can not deal with the locally declared struct.





Like asdf098 says:-





#include %26lt;iostream%26gt;


#include%26lt;vector%26gt;





struct dateStruct


{


int day;


int month;


int year;


};





int main (int argc, char* const argv[])


{


std::vector%26lt;dateStruct%26gt; myVectorOfDateStruct;





struct dateStruct myDateStruct;


myDateStruct.day = 5;


myVectorOfDateStruct.push_back(myDateS...


std::cout %26lt;%26lt; myVectorOfDateStruct.at(0).day;





return 0;


}
Reply:The following will work.





#include%26lt;iostream%26gt;


#include%26lt;vector%26gt;





struct date{


int day;


int month;


int year;


};





int main(){





std::vector%26lt;date%26gt; x;


return 0;


};
Reply:There are two ways in defining a struct... One is at he begining of the code (as a global variable) and the other inside a function as a local variable.


When you define it as a local variable you must give it a name. What you did here was only to specify it's type, not it's name. That's ok if you wanted to declare it globally but this is not the case.





I'll show you a way to do this (there are others as well)





so:





using namespace std;





main() {


struct Date{


int day;


int month;


int year;


} *date; //here I give it a name, in fact this is a pointer to the newly defined Date type





date[0].day=10;


date[0].month=9;


date[0].year=1992; //and so on


return 0;


}





You can do many things with a struct, in fact a struct has the same options as a class (so you can inherit it, define constructors destructors... all the things you can do with a class you can do with a struct as well).


The only difference between the two is that in a struct the local members are by default considered public while in a class they are considered private by default.


No comments:

Post a Comment