473,569 Members | 2,701 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Searching a container

Hello!

I would like to ask how to search for a container element which
matches some criteria.
Here is what I mean.

Suppose I have a structure:
struct my_struct {
my_struct(const std::string &lname, const std::string &lvalue,
const std::string &lothername, const bool lsomething,
const bool lanotherone, const unsigned lunsignedValue)
: name(lname), value(lvalue), othername(lothe rname),
something(lsome thing), anotherone(lano therone),
unsignedValue(l unsignedValue) {}

my_struct() {}

std::string name;
std::string value;
std::string othername;
bool something;
bool anotherone;
unsigned unsignedValue;
};

And I have a vector (or other container) which holds elements of
type my_struct:
std::vector<my_ struct>

I want to search for an element in the container which for example
has name "hello" and an unsignedValue less than 83333.
Or search for an element
which has name "world", value "world", any othername, true for
something
and false for anotherone and any value of unsignedValue. etc.

I have come up with two solutions, both are basically the same, they
use std::find_if using a specially for this purpose written predicate.
They differ only by method how search parameters are passed to the
predicate.

Solution 1:
The constructor of class my_struct_searc her can take all parameters to
be
searched. The ones which do not matter are left default initialized.
To search my_struct::unsi gnedValue a unary predicate can be specified
to my_struct_searc her. If none is specified the default
"DefaultFunctor "
is used which just returns true.

struct DefaultFunctor : public std::unary_func tion<unsigned, bool>
{
bool operator()(cons t unsigned c) const { return true; }
};

template <typename CmpFunctor = DefaultFunctor>
class my_struct_searc her {
private:
CmpFunctor CompareFunction ;
boost::logic::t ribool b_something;
boost::logic::t ribool b_anotherone;
protected:
my_struct local;
public:
my_struct_searc her(
const std::string &name = std::string(),
const std::string &value = std::string(),
const std::string &othername = std::string(),
const boost::logic::t ribool &something =
boost::logic::i ndeterminate,
const boost::logic::t ribool &anotherone =
boost::logic::i ndeterminate,
const CmpFunctor &f = DefaultFunctor( ))
: local(name, value, othername, true, true, 0),
b_something(som ething), b_anotherone(an otherone),
CompareFunction (f) {}

bool operator()(cons t my_struct &ms) {
bool found = true;
found = found && (local.name.emp ty() ||
(ms.name.find(l ocal.name) != std::string::np os));
if (found == false) return false;
found = found && (local.value.em pty() ||
(ms.value.find( local.value) != std::string::np os));
if (found == false) return false;
found = found && (local.othernam e.empty() ||
(ms.othername.f ind(local.other name) != std::string::np os));

return found && baseCompare(ms) ;
}
bool baseCompare(con st my_struct &ms) {
bool found = true;
found = found && (boost::logic:: indeterminate(b _something) ||
(ms.something == b_something));
if (found == false) return false;
found = found && (boost::logic:: indeterminate(b _anotherone) ||
(ms.anotherone == b_anotherone));
if (found == false) return false;

return found && CompareFunction (ms.unsignedVal ue);
}
};

Example of usage:
// find an element in a container which has part of
// name "hell" and unsignedValue < 280
iter = std::find_if(co ntainer.begin() , container.end() ,
my_struct_searc her<std::binder 2nd<std::less<u nsigned> > >("hell",
"", "", boost::logic::i ndeterminate,
boost::logic::i ndeterminate, bind2nd(std::le ss<unsigned>(),
280)));
What I dont like in this solution is that to search using only a
single
criteria which happens to be at the end of constructor (can be
specified
as one of the last parameters of ctor) all the other parameters must
be specified as default. Like: my_struct_searc her<>("", "", "", true),
to search just for my_struct::some thing being true.
Solution 2:
Use the same mechanism as in solution 1, just make specifying search
criteria easier by "chaining up" search parameters by having a
structure (struct nice_params) with member functions which set the
search parameter and return reference to *this.

template <typename CmpFunctor = DefaultFunctor>
class other_searcher {
public:
struct nice_params {
my_struct local;
boost::logic::t ribool b_something;
boost::logic::t ribool b_anotherone;
CmpFunctor CompareFunction ;

nice_params(con st CmpFunctor &f = DefaultFunctor( )) :
CompareFunction (f),
b_something(boo st::logic::inde terminate),
b_anotherone(bo ost::logic::ind eterminate) {}
nice_params &name(const std::string &name) { local.name = name;
return *this; }
nice_params &value(const std::string &value) { local.value =
value; return *this; }
nice_params &othername(cons t std::string &othername) {
local.othername = othername; return *this; }
nice_params &something(cons t boost::logic::t ribool &something)
{ b_something = something; return *this; }
nice_params &anotherone(con st boost::logic::t ribool
&anotherone) { b_anotherone = anotherone; return *this; }
};
protected:
nice_params params;
public:
other_searcher( const nice_params &p) : params(p) {}

bool operator()(cons t my_struct &ms) {
bool found = true;
found = found && (params.local.n ame.empty() ||
(ms.name.find(p arams.local.nam e) != std::string::np os));
if (found == false) return false;
found = found && (params.local.v alue.empty() ||
(ms.value.find( params.local.va lue) != std::string::np os));
if (found == false) return false;
found = found && (params.local.o thername.empty( ) ||
(ms.othername.f ind(params.loca l.othername) != std::string::np os));

return found && baseCompare(ms) ;
}
bool baseCompare(con st my_struct &ms) {
bool found = true;
found = found &&
(boost::logic:: indeterminate(p arams.b_somethi ng) || (ms.something ==
params.b_someth ing));
if (found == false) return false;
found = found &&
(boost::logic:: indeterminate(p arams.b_another one) || (ms.anotherone ==
params.b_anothe rone));
if (found == false) return false;

return found && params.CompareF unction(ms.unsi gnedValue);
}
};

Example of usage:
// search for an element in a container which
// value member contains "is a"
//
iter = std::find_if(vm s.begin(), vms.end(),
other_searcher_ exact<>(other_s earcher<>::nice _params().value ("is
a")));
I like this solution better because search criteria can be
specified nicer.

Could you suggest other ideas/methods how to search such data
structure?
Here is a compilable code of both versions with more usage examples.
http://www.catonmat.net/tmp/cpp.searching.container.txt
Thanks!

--
P.Krumins

Aug 9 '05 #1
3 1446
Why not use another parameter to determine which criterias should be
searched?
I think it is more efficient than your way.

Aug 9 '05 #2
tjsparkle wrote:
Why not use another parameter to determine which criterias should be
searched?
I think it is more efficient than your way.


What do you mean by "another parameter"? Can you give an example?
Thanks,
P.Krumins

Aug 9 '05 #3
On second thoughts, my method was the same as your second one.
I made a mistake. :)

Aug 10 '05 #4

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

Similar topics

2
2033
by: Bryce Maschino | last post by:
hello, i am trying to make a java program that will take several different arrays and search through them in a loop suchs as: for (i=0; i < 5; i++) { if (firstarray<such and such { blah blah
2
6450
by: yee young han | last post by:
I need a fast data structure and algorithm like below condition. (1) this data structure contain only 10,000 data entry. (2) data structure's one entry is like below typedef struct _DataEntry_ { char szInput; char szOutput; int iSum;
3
2620
by: jignesh shah | last post by:
Hi all, Is there a way to recover a single container if its been corrupted or mark bad without restoring whole tablespace? environment: db28.1/aix5.1/tsm/rs-6000. Regards Jignesh
9
1781
by: horizon5 | last post by:
Hi, my collegues and I recently held a coding style review. All of the code we produced is used in house on a commerical project. One of the minor issues I raised was the common idiom of specifing: <pre> if len(x) 0: do_something() </pre>
4
5325
by: Hunk | last post by:
Hi I have a binary file which contains records sorted by Identifiers which are strings. The Identifiers are stored in ascending order. I would have to write a routine to give the record given the Identifier. The logical way would be to read the record once and put it in an STL container such as vector and then use lower_bound to search for...
11
1912
by: jimxoch | last post by:
Hi list, Most STL containers are storing their data on the heap. (although some std::string implementations are notable exceptions) Of course, using the heap as storage increases flexibility and allows the handling of much bigger amounts of data. However, there are cases where this turns out to be inefficient for at least two reasons: A)...
18
1801
by: Goran | last post by:
Hi @ all! Again one small question due to my shakiness of what to use... What is better / smarter? private: vector<MyClass_t* itsVector; OR...
4
1589
by: moswald | last post by:
I've been searching for a specific article for awhile now. About two years ago (maybe longer) there was an article in the C/C++ User's Journal that compared the performances of various stl containers. Unfortunately, while I remember the topic, I don't remember much else, so if anyone is inclined to help me find it, they'll have to do some...
2
1665
by: jimxoch | last post by:
Dear list, I have recently implemented a generic sequence searching template function, named single_pass_search, which is more generic than std::search and has better worst case complexity at the same time. More specifically, the main advantage of the single_pass_search over the std::search is its capability to search for a sub-sequence...
0
7697
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...
0
7924
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. ...
0
8120
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...
1
7672
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...
0
7968
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...
0
6283
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...
1
5512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5219
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...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.