473,785 Members | 2,844 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find algorithm in STL

180 New Member
Hi guys,
I have problem regarding find algorithm used in STL

Defination directly from book
The find algorithm is an operation (function) that can be applied to many STL containers. It searches a subrange of the elements in a container (or all the elements), looking for an element that is "equal to" a specified value; the equality operator (==) must be defined for the type of the container's elements.

In the defination above i'm having problem with the bold text

Now here is myClass as follows

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<vector>
  3. #include<algorithm>
  4. using namespace std;
  5.  
  6. class myClass
  7. {
  8. public:
  9.     myClass(){}
  10.     ~myClass(){}
  11.     friend bool operator==(myClass& a, myClass& b);
  12. };
  13. typedef std::vector<myClass*>            myClassList;
  14. typedef std::vector<myClass*>::iterator   myClassListIterator;
  15.  
  16. bool operator==(myClass& a, myClass& b) //this doesnt get called
  17. {
  18.     return true;
  19. }
  20.  
  21. int main()
  22. {
  23.     myClass* a = new myClass();
  24.     myClass* b = new myClass();
  25.  
  26.     myClassList list;
  27.     list.push_back(a);
  28.     list.push_back(b);
  29.     myClassListIterator it = find(list.begin(), list.end(), a); //should call operator==
  30.     if( it == list.end() )
  31.         cout<<"Not found"<<endl;
  32.     else
  33.         cout<<"Found"<<endl;
  34.     return 0;
  35. }
But the problem is I'm unable to call the operator== defined in myClass. What is that I'm doing wrong in the above code????

Any comment will be highly appreciated
Oct 11 '06 #1
10 21884
arne
315 Recognized Expert Contributor
Hi guys,
I have problem regarding find algorithm used in STL

Defination directly from book
The find algorithm is an operation (function) that can be applied to many STL containers. It searches a subrange of the elements in a container (or all the elements), looking for an element that is "equal to" a specified value; the equality operator (==) must be defined for the type of the container's elements.

In the defination above i'm having problem with the bold text

Now here is myClass as follows

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<vector>
  3. #include<algorithm>
  4. using namespace std;
  5.  
  6. class myClass
  7. {
  8. public:
  9.     myClass(){}
  10.     ~myClass(){}
  11.     friend bool operator==(myClass& a, myClass& b);
  12. };
  13. typedef std::vector<myClass*>            myClassList;
  14. typedef std::vector<myClass*>::iterator   myClassListIterator;
  15.  
  16. bool operator==(myClass& a, myClass& b) //this doesnt get called
  17. {
  18.     return true;
  19. }
  20.  
  21. int main()
  22. {
  23.     myClass* a = new myClass();
  24.     myClass* b = new myClass();
  25.  
  26.     myClassList list;
  27.     list.push_back(a);
  28.     list.push_back(b);
  29.     myClassListIterator it = find(list.begin(), list.end(), a); //should call operator==
  30.     if( it == list.end() )
  31.         cout<<"Not found"<<endl;
  32.     else
  33.         cout<<"Found"<<endl;
  34.     return 0;
  35. }
But the problem is I'm unable to call the operator== defined in myClass. What is that I'm doing wrong in the above code????

Any comment will be highly appreciated

Maybe:
Your vector contains elements of type "myClass*", your operator== however compares elements of type "myClass". So, I would guess pointers to objects and not objects themselves are compared here. Hence, your operator is not called.
Oct 11 '06 #2
zahidkhan
22 New Member
Hi guys,
I have problem regarding find algorithm used in STL

Defination directly from book
The find algorithm is an operation (function) that can be applied to many STL containers. It searches a subrange of the elements in a container (or all the elements), looking for an element that is "equal to" a specified value; the equality operator (==) must be defined for the type of the container's elements.

In the defination above i'm having problem with the bold text

Now here is myClass as follows

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<vector>
  3. #include<algorithm>
  4. using namespace std;
  5.  
  6. class myClass
  7. {
  8. public:
  9.     myClass(){}
  10.     ~myClass(){}
  11.     friend bool operator==(myClass& a, myClass& b);
  12. };
  13. typedef std::vector<myClass*>            myClassList;
  14. typedef std::vector<myClass*>::iterator   myClassListIterator;
  15.  
  16. bool operator==(myClass& a, myClass& b) //this doesnt get called
  17. {
  18.     return true;
  19. }
  20.  
  21. int main()
  22. {
  23.     myClass* a = new myClass();
  24.     myClass* b = new myClass();
  25.  
  26.     myClassList list;
  27.     list.push_back(a);
  28.     list.push_back(b);
  29.     myClassListIterator it = find(list.begin(), list.end(), a); //should call operator==
  30.     if( it == list.end() )
  31.         cout<<"Not found"<<endl;
  32.     else
  33.         cout<<"Found"<<endl;
  34.     return 0;
  35. }
But the problem is I'm unable to call the operator== defined in myClass. What is that I'm doing wrong in the above code????

Any comment will be highly appreciated
Here internally algorithm find is comparing two pointers
Since pointer of your class can't call the == operator
you have to pass the object

And you should use const myClass& as a parameter of == operator
because algorithm find is receiving your object using const & and

and there is no operator defined which will take your operands as const reference

So the final solution is like this


#include<iostre am>
#include<vector >
#include<algori thm>
using namespace std;

class myClass
{
public:
myClass(){}
~myClass(){}
friend bool operator==(cons t myClass& a, const myClass& b); // Modified
};
typedef std::vector<myC lass*> myClassList;
typedef std::vector<myC lass>::iterator myClassListIter ator; // Modified

bool operator==(cons t myClass& a, const myClass& b) //this doesnt get called // Modified
{
return true;
}

int main()
{
myClass* a = new myClass();
myClass* b = new myClass();

myClassList list;
list.push_back( a);
list.push_back( b);
myClassListIter ator it = find(*list.begi n(), *list.end(), *a); //should call operator== // Modified
if( it == *list.end() ) // Modified
cout<<"Not found"<<std::en dl;
else
cout<<"Found"<< std::endl;
return 0;
}
Oct 11 '06 #3
vermarajeev
180 New Member
Hi thankx,
The solution works but I'm not still clear.

Now first thing first, what is the main difference between
Expand|Select|Wrap|Line Numbers
  1. myClassListIterator it = find(list.begin(), list.end(), a); 
and
Expand|Select|Wrap|Line Numbers
  1. myClassListIterator it = find(*list.begin(), *list.end(), *a);
How does the find algorithm interpret that.

My understanding is
I understand that a(in above code) is a pointer and *a(in above code) is an address. Now operator==(cons t myClass& a, const myClass& b) has address in it. So when I use *list.begin(), *list.end() in the above code, their addresses gets passed because of which operator== gets called. Did I make sense?

If not please help me to correct myself.
Thankx
Oct 12 '06 #4
D_C
293 Contributor
*list.begin() is the contents of the first element in the list.
*list.end() is the contents of the last element in the list.

list.end() and list.begin() are pointers, references, and the * is deference. It cancels it out, leaving the original contents, rather than it's address.
Oct 13 '06 #5
dtimes6
73 New Member
Try this:

bool operator==(myCl ass* a, myClass* b)
{
return true;
}
Oct 13 '06 #6
vermarajeev
180 New Member
Try this:

bool operator==(myCl ass* a, myClass* b)
{
return true;
}
When I do that as you have suggested I get the following errors
Expand|Select|Wrap|Line Numbers
  1. : error C2803: 'operator ==' must have at least one formal parameter of class type
  2. : error C2803: 'operator ==' must have at least one formal parameter of class type
Can you help me now....

Thankx
Oct 13 '06 #7
dtimes6
73 New Member
This is an compiler error that it can not compare two pointers.

Use an obj to wrap your pointer, like this.

#include<iostre am>
#include<vector >
#include<algori thm>
using namespace std;

class myClass
{
public:
myClass(){}
~myClass(){}
};

class myClassPtr{
public:
myClass* p;
myClassPtr( myClass* ptr): p(ptr) {}
};

typedef std::vector<myC lassPtr> myClassList;
typedef std::vector<myC lassPtr>::itera tor myClassListIter ator;

bool operator==(cons t myClassPtr& a, const myClassPtr& b) //this doesnt get called
{
return true;
}

int main()
{
myClass* a = new myClass();
myClass* b = new myClass();

myClassList list;
list.push_back( a);
list.push_back( b);
myClassListIter ator it = find(list.begin (), list.end(), a); //should call operator==
if( it == list.end() )
cout<<"Not found"<<endl;
else
cout<<"Found"<< endl;
return 0;
}
Oct 13 '06 #8
vermarajeev
180 New Member
Hi, thankx for your reply...
It works fine but can you please explain me why we need the wrapper class myClassPtr and how that it is working....I'm unable to understrand that...

Waiting for your reply....
Oct 13 '06 #9
dtimes6
73 New Member
The pointer's operator== is a build-in
like bool operator==(int, int)
Oct 13 '06 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

16
2665
by: cody | last post by:
I have to write an algorithm with must ensure that objects are put in buckets (which are always 4 in size). The objects have two properties: A and B. It is not allowed that in a bucket are objects with the same A or B value. But there can be more than one object with A = null or B = null in the bucket. Sometimes there is only one valid solution, sometimes there are more valid solutions, and sometimes there isn't a complete solution at...
4
6490
by: Code4u | last post by:
I need to write an algorithm that sheds the outliers in a large data set, for example, I might want to ignore the smallest 2% of values and find the next smallest. Boost has a nth_element algorithm, however, it partially sorts the data. I have a requirement that the data remain in the orginal order. Of course I could make a copy of the vector or array and then apply nth_element, but this would be expensive in memory and would require...
113
12356
by: Bonj | last post by:
I was in need of an encryption algorithm to the following requirements: 1) Must be capable of encrypting strings to a byte array, and decyrpting back again to the same string 2) Must have the same algorithm work with strings that may or may not be unicode 3) Number of bytes back must either be <= number of _TCHARs in * sizeof(_TCHAR), or the relation between output size and input size can be calculated simply. Has to take into account the...
7
3703
by: Bit byte | last post by:
I have the ff code: list<string> *m_alive_list ; list<string>::iterator my_iter; my_iter = find(m_alive_list->begin(), m_alive_list->end, string(inbox) ; Compiler barfs on 2nd line with this error msg: error C2665: 'std::find' : none of the 3 overloads can convert parameter 1 from type 'std::list<_Ty>::iterator'
5
2580
by: Draw | last post by:
Hi All, Just a thought, about the find() algorithm in the C++ STL. I read that the find algorithm can take a range of iterators. If it does not find the element it is looking for in that range it returns the iterator to the last element in the range, not to the last element in the container, to the last element in the range. That being said, how can we tell if find() has been successful in finding the element we need? Its easy when we...
10
7534
by: Christian Chrismann | last post by:
Hi, I've a question on the STL find algorithm: My code: int main( void ) { vector< ClassA* myVector; ClassA *ptrElement1 = ...;
1
2737
by: vermarajeev | last post by:
Hi, EveryBody This question is really interesting one. My question is related to "STL Find Algorithm" Defination Direct from book Now my questions are
4
32085
prometheuzz
by: prometheuzz | last post by:
Hello (Java) enthusiasts, In this article I’d like to tell you a little bit about graphs and how you can search a graph using the BFS (breadth first search) algorithm. I’ll address, and hopefully answer, the following questions: • what is a graph? • how can a graph be represented as an ADT? • how can we search/walk through a graph using the BFS algorithm?
4
1851
by: indrawati.yahya | last post by:
Just out of curiosity, why doesn't C++ find() accept a binary predicate so users can do equality comparisons other than the == operator? In this case, the use of find() will be similar to sort(), and probably we can do away with find_if(). Like most things in C++, I know there must be a good reason for this, I just cannot figure out what that is at the moment. Thank you.
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10330
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10153
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9952
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.