So I would like to make a function which would add elements in container in sorted manner.
Let's say we have a struct with two integer. I randomly initialize them and the add it to deque. And now what I want is that my function would add them in a way that values would be sorted. Example:
We generate numbers for 6 struct.
1 0
3 6
2 4
0 2
2 1
0 5
What I want now is that my function would add them in that order:
0 2
0 5
1 0
2 1
2 4
3 6
I came up with that, but it does not work. I am kinda new with iterators ... any help is appreciated.
Using the sort() function from <algorithm> we find that there is an overloaded version of sort() that will allow us to supply our own custom-made 'test' function. Let's use this in order to specifically perform a test between two 'deques of structs'. We'll base our test on the 'int a' attribute of the struct:
Aha, I've just quickly tested it and it seems to work!
Here's a little program I knocked up, loosely based around previously posted code in this thread:
for(deque<Str>::iterator iter = deq.begin(); iter!=deq.end(); iter++)
{
cout << "a = " << (*iter).a << ", b = " << (*iter).b << endl;
}
}
And some sample output is shown in the attached .png.
Looking at the png, you can see that there are several values which have an 'a' value of 2. These have successfully been sorted by their 'b' values.
Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.
This thread is more than three months old
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.