Board index » cppbuilder » Find in vector<struct>

Find in vector<struct>


2006-09-29 05:11:55 PM
cppbuilder29
I am using vector to store structures and want to find a vector element and
was hoping to use find in <algorithm>but the best I could come up with was
using find_if. This seems convoluted to me and was wondering if there is a
better or simpler way?
The convoluted code I came up that seems to work is:
typedef struct _TST
{
std::string sTest;
int nTest;
double dTest;
} TST;
TST stTst;
double Find(vector<TST>vTest, string sFind)
{
static string _sFind;
_sFind = sFind;
class _local
{
private: static bool Predicate(TST stFind)
{
if ( stFind.sTest == _sFind )
return true;
else
return false;
}
public: static double Find(vector<TST>vTest,string sFind)
{
vector<TST>::iterator it;
it = find_if(vTest.begin(),vTest.end(),Predicate);
return (*it).dTest;
}
};
return _local::Find(vTest,sFind );
}
//*****************************************************************************
void TestFind()
{
vector<TST>vTest;
vector<TST>::iterator it;
for (int i = 0; i < 10 ;++i)
{
stTst.sTest = "Test " + (string)IntToStr(i).c_str();
stTst.nTest = i;
stTst.dTest = i * 3.14159265;
vTest.push_back(stTst);
} // End of For ()
for (int i = 0; i < 10 ;++i)
{
cout << "i = " << i << " " << vTest[i].sTest << " i*PI = " <<
vTest[i].dTest << endl;
} // End of For ()
cout << endl << "Found: " << Find(vTest,"Test 4") << endl;
}
 
 

Re:Find in vector<struct>

"Roger" < XXXX@XXXXX.COM >wrote in message
Quote
the best I could come up with was using find_if.
You are only matching structure instances on one element, so you have to use
find_if() anyway in order to do that.
Quote
The convoluted code I came up that seems to work is:
Try this code instead:
struct TST
{
std::string sTest;
int nTest;
double dTest;
};
struct MatchTST
{
std::string _sFind;
MatchTST(const string &sFind)
: _sFind(sFind)
{
}
bool operator ()(const TST &stFind)
{
return (stFind.sTest == _sFind);
}
};
double Find(const vector<TST>&vTest, const std::string &sFind)
{
vector<TST>::iterator it = find_if(vTest.begin(), vTest.end(),
MatchTST(sFind));
return (*it).dTest;
}
void TestFind()
{
vector<TST>vTest;
for(int i = 0; i < 10; ++i)
{
stTst.sTest = "Test " + std::string(IntToStr(i).c_str());
stTst.nTest = i;
stTst.dTest = i * 3.14159265;
vTest.push_back(stTst);
}
for(int i = 0; i < 10; ++i)
cout << "i = " << i << " " << vTest[i].sTest << " i*PI = "
<< vTest[i].dTest << endl;
cout << endl << "Found: " << Find(vTest, "Test 4") << endl;
}
Gambit
 

Re:Find in vector<struct>

Thanks Remy that works like a charm!
 

{smallsort}