Why the output of c++ multiset is not sorted?
and here is the code
#include
#include
employing namespace std;
int key ()
multisetmyset;
multiset::iterator it;
int arr=5, SEVERAL, 2, SEVERAL, 7, 9, 8, 4, 5;
myset.insert(arr, arr+9);
for(it=myset.begin(); it! =myset.end(); ++it)
cout<<*it<<" ";
cout<<endl;
pair<multiset::iterator, multiset::iterator>ret;
ret=myset.equal_range(5);
for(it=ret.very first; it! =ret.next; ++it)
(int)*it=(*it)*(*it);
for(it=myset.begin(); it! =myset.end(); ++it)
cout<<*it<<" ";
cout<<endl<<endl;
getchar();
returning 0;
what i obtained is
A COUPLE OF 3 THREE OR MORE 4 SOME 5 7 8 9
A COUPLE OF 3 THREE OR MORE 4 TWENTY FIVE 25 7 8 9
i understand the
ret=myset.equal_range(5);
for(it=ret.very first; it! =ret.next; ++it)
(int)*it=*it**it;
got this 5s in the multiset to help 25, but why it’s not sorted just as 1st distinct result and steps to make it turn out to be sorted once more with smallest change
You have one on the particular line
(int)*it=(*it)*(*it);
“it” here is an iterator proper multiset, which dereferences into a const int, which you might be C-casting into a mutable int, and then you’re trying to assign to help it, which is undefined habits if the item compiles in any respect.(gcc, clang++, Intel C++ rejected to put together this, only Visual Studio did, which has a warning)
There is no way in order to modify keys within a set/multiset/map/multimap in-place; they are read-only.You must remove those people keys with the container, alter them, in addition to reinsert.
For any minimal change towards your program, replace
pair<multiset::iterator, multiset::iterator>ret;
ret=myset.equal_range(5);
for(it=ret.very first; it! =ret.next; ++it)
(int)*it=(*it)*(*it);
with
fill_n(inserter(myset, myset.end()), myset.erase(5), 5*5);
(remember to #include regarding fill_n() and #include regarding inserter())
experiment (with different simplifications):
https://ideone.com/9Rp6Q.
Leave a Reply
You must be logged in to post a comment.