Customclass Vector Exercse Year2
Customclass Vector Exercse Year2
class person
{
int age;
string name ;
public:
person(const int age, const string name);
int getage() const;
string getname() const ;
//....
};
it is possible to create a menu option
//vector : copy
// : sort ; ascending, descending ...
// : find
Here is an example using a custom class B in vector..
#include <vector>
#include <bits/stdc++.h>
using namespace std;
class B {
int x;
public:
B(const int xx=0):x(xx){ }
void setx(const int xx ){
x=xx;
}
int getx() const { return x;}
friend int compareascending(const B &a, const B &b);
friend int comparedescending(const B &a, const B &b);
// this operator is using to find custom object
friend bool operator==(const B &a, const B &b){
cout <<"calling ==" <<endl;
return a.x==b.x;
}
};
int compareascending(const B &a, const B &b){
return a.getx() < b.getx();
}
int comparedescending(const B &a, const B &b){
return a.getx() > b.getx();
}
int main()
{
int array[]={20,4,3,5,8,9};
int n=sizeof(array)/sizeof(array[0]);
vector<B> myb;
vector<B*> myc; // object as pointer
// adding element to normal object
for(int i=0;i<n;++i)
myb.push_back(B(array[i]));
// adding elements to pointer object
// so constructor need using new operator is new B(?)
for(int i=0;i<n;++i)
myc.push_back(new B(array[i]));
sort(myb.begin(),myb.end(),compareascending);
cout <<"elements myb\n" ;
for(auto obj:myb)
cout <<obj.getx() <<endl;
reverse(myb.begin(),myb.end());
cout <<"reverse elements myb\n" ;
for(auto obj:myb)
cout <<obj.getx() <<endl;
// finding an element of vector
int value;
cout <<"enter a find element ?";
cin>> value;
vector<int> l{1,2,4,5,100};
auto item=find(l.begin(),l.end(),100);
if(item!=l.end())
cout <<"found " <<endl;
else cout <<"not found " <<endl;
cout <<"enter v ?";
cin>>value;
auto it=find(myb.begin(),myb.end(),B(value));
if(it!=myb.end())
cout <<"The element "<< value << " found at pos :"
<<it-myb.begin() <<endl;
else
cout <<"The element " << value <<"not found " <<endl;