Hi,
The following code works fine:
// main.cpp
#include "Dog.h"
void details(Dog x){
cout << x.height << endl;}
int main()
{
int h,w;
vector<Dog> vect;
cout << "Please enter 3 dogs measurements: "<< endl;
for(int i=0; i<3; i++){
cout <<"\nInput height:" <<endl ;
cin>> h;
cout <<"Input weight:" <<endl ;
cin>> w;
vect.push_back(Dog(h,w));
}
sort(vect.begin(), vect.end());
for_each(vect.begin(), vect.end(), details);
}
The problem is, i want the details() function to be in the Dog class but i do not know how to call the details() function (in the Dog class) when i do it this way..Ive tried the following way:
// main.cpp
#include "Dog.h"
int main()
{
int h,w, index=0;
vector<Dog> vect;
cout << "Please enter 3 dogs measurements: "<< endl;
for(int i=0; i<3; i++){
cout <<"\nInput height:" <<endl ;
cin>> h;
cout <<"Input weight:" <<endl ;
cin>> w;
vect.push_back(Dog(h,w));
}
sort(vect.begin(), vect.end());
for_each(vect.begin(), vect.end(),vect[index].details);
}
// Dog.cpp
#include "Dog.h"
using namespace std;
Dog::Dog(int aHeight, int aWeight):
height(aHeight), weight(aWeight){}
void Dog::details(Dog x){
cout << x.height << endl;}
// Dog.h
#ifndef Dog_h
#define Dog_h
using namespace std;
class Dog{
public:
int ID, height, weight;
public:
Dog(int aHeight, int aWeight);
Dog(){};
bool operator < (const Dog& d) const {
return (height < d.height ? true : false ); } // 17.inline methods
bool operator == (const Dog& d) const {
return (height == d.height ? true : false );}
int getID(){return ID;} //17. Inline methods..
void setID(int newID){ID=newID;}
void details(Dog x);
}
}
but im getting the following error:
main1.cpp:26: error: no matching function for call to `for_each(__gnu_cxx::__normal_iterator<Dog*, std::vector<Dog, std::allocator<Dog> > >, __gnu_cxx::__normal_iterator<Dog*, std::vector<Dog, std::allocator<Dog> > >, <unknown type>)'
C:/Dev-Cpp/include/c++/3.4.2/bits/stl_algo.h:153: note: candidates are: _Function std::for_each(_InputIterator, _InputIterator, _Function) [with _InputIterator = __gnu_cxx::__normal_iterator<Dog*, std::vector<Dog, std::allocator<Dog> > >, _Function = void (Dog::*)(Dog)]
Can someone see wats wrong?
Thanks