• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 170
  • Last Modified:

vector find / operator ==


Trying to iron out more misunderstandings.

Consider:
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

class data {
public:
   int id;
   data(int idx) : id(idx) { }
   data(data*);  //conversion constructor
   bool operator== (const data& data_)  const
   {
     return (data_.id == id);
   };
 };

bool operator==(data *&a, const data &b)
{
  return *a==b;
};

int main()
{
  data* a = new data(1);
  data* b = new data(2);
  data* c = new data(3);
  data* element = new data(3);

  vector<data*> dataset;  
  dataset.push_back(a);    // should be using smat pointer here per the text.. Investigate!!!
  dataset.push_back(b);
  dataset.push_back(c);

  vector<data*>::iterator search = find(dataset.begin(), dataset.end(),
                                                          *element);
   if(search != dataset.end())
   {
        cout<<"found"<<endl;
        cout << dataset[search - dataset.begin()]<<endl;
    }
   else
   {
     cout<<"can't find"<<endl;
   }
}

For this to work I'm not understanding why i need the function:
  bool operator==(data *&a, const data &b)
Now given:
  data a;
  data b;
  a = b;
This equates to:
  a.operator(b);  

Whats the equivalent for operator==(data *&a, const data &b) when called via the find algorithm?

2.  I'd like to print the value but  " dataset[search - dataset.begin()] " gives me the address
0
forums_mp
Asked:
forums_mp
1 Solution
 
efnCommented:
a == b

is equivalent to

a.operator ==(b)

or

operator ==(a, b)

If that doesn't answer your question, please clarify it.

2.  There is some kind of iterator difference function in the standard library, but it would be simpler just to dereference the iterator.  search is like a pointer to an element of dataset, so *search is a pointer to a data, and *search gives you what you are trying to get with " dataset[search - dataset.begin()]".

--efn
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now