Suppose I have dozens of geographic regions, which can be defined through the use of the following c/c++ structure:
typedef struct tagGEOGRAPHIC_REGION
{
float fNorthMost;
float fSouthMost;
float fWestMost;
float fEastMost;
} GEOGRAPHIC_REGION, *PGEOGRAPHIC_REGION;
And I now want to get the maximum region, which will cover all given regions. The function template may look like the following:
const GEOGRAPHIC_REGION& GetMaxRegion(const std:vector<GEOGRAPHIC_REGION>& vRegions)
{
......
}
I can put the four components of GEOGRAPHIC_REGION struct into 4 different float vectors, and then evaluate thei开发者_开发问答r respective maximum values. Finally, the four maxium values can be combined to form the maximum region. I think it must be a simple way to do that. Would you please give me some advice? Thank you very much!
Can't you just iterate over the vector, and get the maximum north, minimum south, etc, with just one loop?
I suggest something like this as a starting point:
- see it live: http://ideone.com/LQk8U
note that I might have your axis direction guessed wrong (you might need to swap some min/max in that case)Edit fixed according to comment "North is positive, and East is positive"for a vector, just do
std::acummulate(v.begin(), v.end(), v[0]....)
In case your scenarios get more complicated, see the Boost Geometry Library
.
#include <iostream>
#include <numeric>
struct GEOGRAPHIC_REGION
{
float fNorthMost;
float fSouthMost;
float fWestMost;
float fEastMost;
};
GEOGRAPHIC_REGION combine(const GEOGRAPHIC_REGION& accum, const GEOGRAPHIC_REGION& tocombine)
{
GEOGRAPHIC_REGION combined = {
std::max(accum.fNorthMost, tocombine.fNorthMost),
std::min(accum.fSouthMost, tocombine.fSouthMost),
std::min(accum.fWestMost, tocombine.fWestMost),
std::max(accum.fEastMost, tocombine.fEastMost)
};
return combined;
}
int main()
{
const GEOGRAPHIC_REGION regions[] =
{
{ 2,-1,-1,1 },
{ 1,-2,-1,1 },
{ 1,-1,-2,1 },
{ 1,-1,-1,2 },
};
GEOGRAPHIC_REGION super = std::accumulate(regions, regions+4, regions[0], combine);
std::cout << "{ " << super.fNorthMost << ", "
<< super.fSouthMost << ", "
<< super.fWestMost << ", "
<< super.fEastMost << " }" << std::endl;
}
精彩评论