Structs

Structs and overloading operators

#include <iostream>
using namespace std;

struct stud{
    string name;
    int age;
};


int main(){
    stud a,b;
    a.name="bob";
    a.age=19;
    b=a;
    cout<<b.name << b.age;

    return 0;
}

Overriding ctor

#include <iostream>
using namespace std;

struct Stud{
    Stud(); //default ctor
    Stud(string , int  ); //variables optional
    string name;
    int age;
};

Stud::Stud(){}

Stud::Stud(string n, int a){
    name=n;
    age=a;
}

int main(){
    Stud a;
    Stud b("mary",22);
    a.name="bob";
    a.age=19;
    cout<<b.name << b.age;
    b=a;
    cout<<b.name << b.age;

    return 0;
}

Initialization lists


#include <iostream>
using namespace std;

struct Stud{
    string name;
    int age;
    Stud(): name(" "), age(0){}
    Stud(string n, int a): name(n), age(a){}
    //Stud();
    //Stud(string , int ); //variables optional
};
//struct initialization list
//Stud::Stud(){}
//Stud::Stud(): name(" "), age(0){}
//Stud::Stud(string n, int a) : name(n), age(a) {}

int main(){
    Stud a;
    cout<<a.name<<a.age<<endl;

    Stud b("mary",22);
    a.name="bob";
    a.age=19;
    b=a;
    cout<<b.name<<b.age<<endl;

    return 0;
}

Overloading insertion («) and less than (<) operators


#include <iostream>
using namespace std;

struct stud{
    string name;
    int age;
};

ostream& operator<<( ostream &o, const stud &s){
    o << s.name << " " << s.age;
    return o;
}

bool operator<(const stud &x, const stud &y){
    return (x.age < y.age);
}

int main(){
    stud a,b;
    a.name="bob";
    a.age=19;
    b.name="sarah";
    b.age=20;
    //cout<<b.name << b.age;

    cout << b <<endl;

    if (a<b)
    {
        cout<<a.name<<" is younger than "<<b.name<< endl;
    }


    return 0;
}

Sorting people in files with structs

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
//sort mydata people by age
struct person
{
    string name;
    int age;
};

//define < operator for persons to be sortable
// ex. if p1 < p2     pass by const reference
bool operator< (const person &p1, const person &p2)
{
    return (p1.age < p2.age);
}

//define insertion operator for persons
// cout << p1
ostream& operator<< (ostream &o, const person &p)
{
    o<<p.name<<" "<<p.age;
    return o;
}

istream& operator>> (istream &i,  person &p)
{
    i>>p.name>>p.age;
    return i;
}

int main()

{

    vector <person> list;
    ifstream inf;
    inf.open("mydata.txt", ios::in);
    person temp;
    while ( inf>>temp ) //extraction operator >> (space or newline delimeted)
    {
        list.push_back(temp);
    }
    inf.close();
    sort(list.begin(),list.end());
    ofstream outf;
    outf.open("newdata.txt", ios::out);
    for (unsigned int x=0; x<list.size(); x++)
    {
        outf << list[x] << endl;
    }
    outf.close();
    return 0;
}