问题
I want to fill some structure while finding minimum element. Pl find the code below
tyoedef struct Point
{
double x, y;
}Point;
I have a vector of points
- std::vector<Point> V
in which i have few thousand points.
There is another struct I have
typedef struct cart
{
Point pt;
double val_1; // computed using only Pt
double val_2; // computer using only Pt
}cart;
Now I have two tasks:
- I need to find minimum element from structure V.
Fill the structure cart, which is directly dependent on V.
I can do this using following code.
std::vector<cart> vCart; for(unsigned i = 0; i < V.size(); ++i) { cart thsElement; thsElement.pt = V[i]; thsElement.val_1 = compute_val_1(V[i]); thsElement.val_2 = compute_val_2(V[i]); vCart.push_back(thsElement) } auto it = std::min_element(vCart.begin(), vCart.end(), lex_sort); bool lex_sort(cart const &a, cart const &b) { if(a.pt.x < b.pt.x) return true; if(a.pt.x == b.pt.x) return (a.pt.y < b.pt.y); }
Now there is an evident problem with this implementation.
There are two loops. One for filling the structure and other for finding the min element (std::min_element()
has to have a loop to iterate over all the values). I am fighting for few miliseconds' improvement. So this is not a good code. Moreover, this seems so C_style
So I came up with following code.
std::vector<cart> vCart;
std::iterator <vCart> st_ite;
auto it = std::min_element(V.begin(), V.end(), boost::bind(FillStruct_LexSort, st_ite, _1, _2)); // V is a vector of Point
bool FillStruct_LexSort(std::insert_iterator< std::vector<Cart>> vcpInput, const Point &a, const Point &b)
{
Cart thsPt;
if(a.x() < b.x())
{
thsPt.pt = b;
thsPt.val_1 = compute_val_1(b);
thsPt.val_2 = compute_val_2(b);
(*vcpInput++) = (thsPt);
return true;
}
if (a.x() == b.x())
{
if(a.y() < b.y())
{
thsPt.pt = b;
thsPt.val_1 = compute_val_1(b);
thsPt.val_2 = compute_val_2(b);
(*vcpInput++) = (thsPt);
return true;
}
}
thsPt.pt = a;
thsPt.val_1 = compute_val_1(b);
thsPt.val_2 = compute_val_2(b);
(*vcpInput++) = (thsPt);
return false;
}
Now, the problem is - I get segmentation fault. I do not know how should I use iterator to insert a value. I tried passing reference to vCart, but vCart is empty after calling min_element(..). I even tried insert_iterator, but with no success.
So pl suggest.
回答1:
It seems you want something like:
bool lex_sort(const Point& lhs, const Point& rhs)
{
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
and then
auto it = std::min_element(V.begin(), V.end(), &lex_sort);
if (it == V.end()) {
// V is empty.
} else {
Cart thsPt;
thsPt.pt = it;
thsPt.val_1 = compute_val_1(*it);
thsPt.val_2 = compute_val_2(*it);
return thsPt;
}
Note that if val_1
/val_2
always depend of pt
, you can add a constructor for Cart
which take a Point
来源:https://stackoverflow.com/questions/34559219/fill-structure-while-finding-min-element-c