Re: STL Vector Access
mrc2323@cox.net (Mike Copeland) wrote:
I am converting an application element which currently is a fixed
array, sorted for searching by a binary search. Because I don't want to
maintain this process with a fixed array size limitation, I decided to
change it to use of an STL vector.
However, the binary search function is in a subprocess, and I'm
calling it with a parameter that returns the index of the matched
element. The function is a boolean function. Now that I've changed the
processing, I find that I don't know how to access the matched element
(if a match is made), because I'm using an iterator to search the
vector.
Is there a way I can return to the calling code an offset or index to
the matched vector element? TIA
Here's the search code:
bool findTeamId(int *pp) // Find Team Id
{
bool bFound = false;
string strTId = sTId;
strcpy(TeamId, copy(B40, 1, 26)), *pp = -1; // defaults
for(tIter = teamVector.begin(), bFound = false; tIter !=
teamVector.end(); tIter++)
{
if(strTId == tIter->teamCode)
{
// How can I assign pp - or is there another way to access the matched
// element?
return true;
}
}
return bFound;
}
The above seems confused. You talk about doing a binary search, but then
show a linear search in your code. You say you are calling your binary
search function "with a parameter that returns the index of the matched
element." Do you mean you are passing a function pointer to the binary
search function? If I ignore the above code and assume you are asking
how to do a binary search on a sorted vector, then I come up with the
following:
typedef vector<TeamData> TeamVector;
typedef TeamVector::iterator TeamIter;
TeamVector teamVector;
string teamCode;
// fill the teamVector, assign to teamCode
// sort the vector
sort(teamVector.begin(), teamVector.end(), TeamDataCodeCompare());
// find the TeamData object
TeamIter it = lower_bound(teamVector.begin(), teamVector.end(),
teamCode, TeamDataCodeCompare());
if (it != teamVector.end() && it->teamCode == teamCode) {
// 'it' points to the TeamData object you are looking for.
// if more than one TeamData object has the same code, 'it'
// points to the first one in the vector that has the code.
}
in the above code 'TeamDataCodeCompare' is defined as follows:
struct TeamDataCodeCompare
{
bool operator()(const TeamData& lhs, const TeamData& rhs) const {
return lhs.teamCode < rhs.teamCode;
}
bool operator()(const TeamData& lhs, const string& rhs) const {
return lhs.teamCode < rhs;
}
bool operator()(const string& lhs, const TeamData& rhs) const {
return lhs < rhs.teamCode;
}
};
Hope this helps.