473,666 Members | 2,167 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

STL find algorithm

Hi,

I've a question on the STL find algorithm:
My code:

int main( void )
{
vector< ClassA* myVector;

ClassA *ptrElement1 = ...;

myVector.push_f ront( ptrElement1 );
...

ClassA *ptrElement2 = *(myVector.begi n());

vector< ClassA* >::iterator it =
find( myVector.begin( ), myVector.end(), ptrElement2 );

...
}

What is used here in the 'find' algorithm for finding 'ptrElement2'?
Since 'ptrElement2' is just a pointer (so it's a variable storing an
address), I assume that each element (also pointers) in the list is
compared with 'ptrElement2' by using the operator== on the
addresses they represent, i.e. it is checked if

(address stored in any element in the list) ==
(address stored in 'ptrElement2')

Is my assumption correct?

However, this is probably rarely wanted. Usually one want to compare
the objects (and not their addresses). To achieve this, one must
dereference ptrElement2 in the 'find' algorithm and additionally make sure
that ClassA provides a proper operator==. Right?

Regards,
Chris
Aug 20 '06 #1
10 7522
Christian Chrismann wrote:
Is my assumption correct?
Yes
Usually one want to compare
the objects (and not their addresses). To achieve this, one must
dereference ptrElement2 in the 'find' algorithm and additionally make sure
that ClassA provides a proper operator==. Right?
Yes, one way of doing this is to use find_if and provide a function as
the third argument defined as:

bool comp(ClassA const* lhs, ClassA const* rhs) { return *lhs == *rhs; }

Another one is to make your ClassA (cheaply) copyable:

class ClassA
{
public:
// ctor, functions, but no data members, which all live in impl

operator ==(ClassA const& other);
private:
boost::shared_p tr< Impl impl;
};

That way, it's cheap and feasible to use a vector of ClassAs directly
and thus you can search for it directly. Classes you use as types and
deal with very often are worth building that way.

Then there are some more bizarre alternatives, all of them require boost:

- boost::lambda

find_if(myVecto r.begin(), myVector.end(), *_1 == someClassA)

- boost::indirect _iterator

boost::indirect _iterator< ClassA const* >
indirect_first( myVector.begin( )), indirect_last(m yVector.end());
find(indirect_f irst, indirect_last, someClassA);

- boost::pointer_ container

boost::ptr_vect or< ClassA myPVector;
find(myPVector. begin(), myPVector.end() , someClassA);
I would use one of the first two solutions at first though.

Jens
Aug 20 '06 #2

"Christian Chrismann" <pl*****@yahoo. deskrev i meddelandet
news:44******** **************@ newsspool1.arco r-online.net...
Hi,

I've a question on the STL find algorithm:
My code:

int main( void )
{
vector< ClassA* myVector;
It is very unusual to store pointers in a vector. It leads to all
kinds of "interestin g" problems. The standard containers are designed
to be value based.
>
ClassA *ptrElement1 = ...;

myVector.push_f ront( ptrElement1 );
...

ClassA *ptrElement2 = *(myVector.begi n());

vector< ClassA* >::iterator it =
find( myVector.begin( ), myVector.end(), ptrElement2 );

...
}

What is used here in the 'find' algorithm for finding 'ptrElement2'?
Since 'ptrElement2' is just a pointer (so it's a variable storing an
address), I assume that each element (also pointers) in the list is
compared with 'ptrElement2' by using the operator== on the
addresses they represent, i.e. it is checked if

(address stored in any element in the list) ==
(address stored in 'ptrElement2')

Is my assumption correct?
Right. You store pointers in the vector, so the find() looks for a
specific pointer.
>
However, this is probably rarely wanted. Usually one want to compare
the objects (and not their addresses). To achieve this, one must
dereference ptrElement2 in the 'find' algorithm and additionally
make sure
that ClassA provides a proper operator==. Right?
Yes. There is another variant of std::find, find_if, that instead of a
value take a function or a function like object. That way you can get
any kind of comparison you like.

The easier way if of course to store the ClassA objects in the vector,
and not use pointers.
Bo Persson
Aug 20 '06 #3
Bo Persson wrote:
>
"Christian Chrismann" <pl*****@yahoo. deskrev i meddelandet
news:44******** **************@ newsspool1.arco r-online.net...
>Hi,

I've a question on the STL find algorithm:
My code:

int main( void )
{
vector< ClassA* myVector;

It is very unusual to store pointers in a vector. It leads to all
kinds of "interestin g" problems. The standard containers are designed
to be value based.
Why would it be unusual? Storing pointers to objects that are owned by
some other entity in a vector is fairly common and there is nothing
wrong with it.

Aug 20 '06 #4
Jens Theisen wrote:
Christian Chrismann wrote:
>Is my assumption correct?

Yes
>Usually one want to compare
the objects (and not their addresses). To achieve this, one must
dereference ptrElement2 in the 'find' algorithm and additionally make
sure that ClassA provides a proper operator==. Right?

Yes, one way of doing this is to use find_if and provide a function as
the third argument defined as:

bool comp(ClassA const* lhs, ClassA const* rhs) { return *lhs == *rhs;
}
Doesn't work. find_if expects a predicate as its third argument not a
comparison function. You would need something like (not tested):

class Comp
{
public:
Comp(const ClassA *const p) : p_(p) {}
bool operator()(cons t ClassA *const q) {return *q == *p_;}

private:
const ClassA *p_;
};

Aug 20 '06 #5
Markus Schoder wrote:
Bo Persson wrote:
>"Christian Chrismann" <pl*****@yahoo. deskrev i meddelandet
news:44******* *************** @newsspool1.arc or-online.net...
>>Hi,

I've a question on the STL find algorithm:
My code:

int main( void )
{
vector< ClassA* myVector;
It is very unusual to store pointers in a vector. It leads to all
kinds of "interestin g" problems. The standard containers are designed
to be value based.

Why would it be unusual? Storing pointers to objects that are owned by
some other entity in a vector is fairly common and there is nothing
wrong with it.
Not to mention that storing pointers in a vector (or any other
container) is the only way to store polymorphic objects in it.
Aug 20 '06 #6
red floyd wrote:
Markus Schoder wrote:
>Bo Persson wrote:
>>"Christian Chrismann" <pl*****@yahoo. deskrev i meddelandet
news:44****** *************** *@newsspool1.ar cor-online.net...
Hi,

I've a question on the STL find algorithm:
My code:

int main( void )
{
vector< ClassA* myVector;
It is very unusual to store pointers in a vector. It leads to all
kinds of "interestin g" problems. The standard containers are
designed to be value based.

Why would it be unusual? Storing pointers to objects that are owned
by some other entity in a vector is fairly common and there is
nothing wrong with it.

Not to mention that storing pointers in a vector (or any other
container) is the only way to store polymorphic objects in it.
Fortunately not the only way. I happen to use smart pointer objects for
that mostly.

Aug 20 '06 #7

"Markus Schoder" <a3************ *@yahoo.deskrev i meddelandet
news:44******** **************@ newsspool1.arco r-online.net...
Bo Persson wrote:
>>
"Christian Chrismann" <pl*****@yahoo. deskrev i meddelandet
news:44******* *************** @newsspool1.arc or-online.net...
>>Hi,

I've a question on the STL find algorithm:
My code:

int main( void )
{
vector< ClassA* myVector;

It is very unusual to store pointers in a vector. It leads to all
kinds of "interestin g" problems. The standard containers are
designed
to be value based.

Why would it be unusual? Storing pointers to objects that are owned
by
some other entity in a vector is fairly common and there is nothing
wrong with it.
Ok, I take back the "very" from "very unusual".

We have had several posters today that attempt to store pointers or
references in a vector or a list, to try to gain some perceived
efficiency. Instead they got all kinds of problems, like lifetimes,
ownership, and extra indirections. Not to mention additional code to
compensate for the "efficiency " of not copying their objects.

The standard way is to store values in the containers, and let them
manage lifetimes, etc.

If you know what you are doing, and are extra careful, you can store
pointers as well, but it is generally not a good idea. This is where
you have the option of blowing your leg off.
Bo Persson
"In C++ it's harder to shoot yourself in the foot, but when you do,
you blow off your whole leg."
- Bjarne Stroustrup.

Aug 20 '06 #8
Markus Schoder wrote:
Doesn't work. find_if expects a predicate as its third argument not a
comparison function. You would need something like (not tested):
True

Jens
Aug 20 '06 #9
Markus Schoder wrote:
red floyd wrote:
>Not to mention that storing pointers in a vector (or any other
container) is the only way to store polymorphic objects in it.

Fortunately not the only way. I happen to use smart pointer objects for
that mostly.
The Standard doesn't provide any smart pointers (no, auto_ptr<doesn' t
count), and some of us don't have access to Boost (for various reasons).
Aug 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5107
by: kittykat | last post by:
Hi, I was wondering if you could help me. I am writing a program in C++, and the problem is, i have very limited experience in this language. I would like my user to enter a specific pattern, and I want my program to search a text file for this pattern, and let the user know if this pattern exists or not. So far, i have figured out how to make my prgram read the text file, but i'm not sure how to take the information the user inserts...
4
6478
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...
1
2637
by: aredo3604gif | last post by:
On Sun, 10 Apr 2005 19:46:32 GMT, aredo3604gif@yahoo.com wrote: >The user can dynamically enter and change the rule connection between >objects. The rule is a "<" and so given two objects: >a < b simply means that b < a can't be set, also it must be a != b. >And with three objects a < b , b < c means a < c > >I studied Quick Union Find algorithms a bit and if I understood them >correctly, once the user gives the input setting the...
6
11204
by: Ravi | last post by:
Hi, I need to find the non-recursive algorithm to find the height of a Binary Tree. Regards, SunLight.
5
3012
by: Mike Labosh | last post by:
In VB 6, the Form_QueryUnload event had an UnloadMode parameter that let me find out *why* a form is unloading, and then conditionally cancel the event. In VB.NET, the Closing event passes a CancelEventArgs that lets me cancel the Close() operation, but is there still any way to find out *why* a form is closing? This app as a form that needs to be loaded at startup, closed only at shutdown, and then Show() / Hide() for the user. If...
5
2573
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...
1
2723
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
10
21877
by: vermarajeev | last post by:
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...
10
13629
by: socondc22 | last post by:
my program is trying to use the babylonian algorithm in order to find the square root... i have a number for the number to have the square root taken of and also a number to run the loop... Whenever i go to print out the answer its rounding instead of giving me the answer i need... any help?? double num1, num2, the_root; cout<< "Enter number to have square root taken of it\n"; cin>> num1; cout<< "Enter number for how...
0
8360
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,...
1
8556
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
8642
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
7387
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4371
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2774
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
2
1777
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.