josh130 josh130 - 1 year ago 109
C++ Question

c++ multiset iterator sorting

I have a multiset

i where I sort according to a class member

I want then to check for all sorted elements, if the difference in
for neighbour fields of
is less than my given threshold, say 0.001. If so, then I want to prefer that which has a smaller another class member, m_b.

Here I am stuck, I have no experience with multiset or iterators. I don't know how to compare iterators from two iterations. If you can provide me with a right code for this what I want to do, will be very grateful!
My try, not too much, just my concept:

//all before I got stuck
for(it = mymulti.begin(); it!= mymulti.end(); ++it) //or it++?
if( (it+1)->mymulti.m_a - (it)->mymulti.m_a < 0.001)
if ((it+1)->mymulti.m_b < (it)->mymulti.m_b)
//swap them. but how to swap two fields in a multiset, not two multisets?
// otherwise do nothing

Answer Source

You cannot (or if you can, depending on your STL implementation, should not) modify items once they have been inserted into a multiset, as it could violate the provided ordering of the items in the multiset. So swapping would be a bad idea, even if you could do it.

See and

If you would like to remove items, use multiset::erase, which takes an iterator. I believe the standard practice for "modifying" an item in a multiset is to remove it, then insert the modified version.

As a side note, I noticed you're checking if two floating point numbers are close enough in value by using a fixed epsilon (0.001). As explained in this article, this only works if all the floats you are comparing are sufficiently small. See the article for a comparison that works equally well for large and small floating-point values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download