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.
#include <iostream>
#include <deque>
#include <ctime>
#include <cstdlib>
using namespace std;
struct Str
{
int a,b;
Str(int aa, int bb): a(aa), b(bb){}
};
void m_Add(const Str& str, deque<Str>& deq)
{
if (deq.empty()) deq.push_back(str);
else
{
deque<Str>::iterator it = deq.begin();
for (int i = 0, size = deq.size(); i < size; i++)
{
if (str.a != deq[i].a)
{
it++;
}
else break;
}
for (int i = 0, size = deq.size(); i < size; i++)
{
if (str.b > deq[i].b)
{
it++;
}
else break;
}
deq.insert(it, str);
}
}
int _tmain()
{
srand((unsigned)time(NULL));
deque<Str> deq;
for (int i(0); i < 10; i++)
{
for (int j = 0; j < 15; j++)
{
Str a(rand()%3, rand()%6);
m_Add(a,deq);
}
}
for (int i = 0, size = deq.size(); i < size; i++)
{
cout << deq[i].a << " " << deq[i].b << endl;
}
return 0;
}