Click here to Skip to main content
15,903,201 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Can anyone find a solution for this???

I want to insert some values to a buffer. But at the same time i need to get that buffer in sorted order. ie,

If i insert 10, buffer should look like this 10
If i insert 20, buffer should look like this 10, 20
If i insert 5, buffer should look like this 5,10, 20
If i insert 15, buffer should look like this 5,10,15,20
If i insert 50, buffer should look like this 5,10,15,2,50

That is, after inserting all elements, i need to get a sorted buffer.

Now I am using a vector to push back the elements, copies all elements to a int* buffer and then sort that int* buffer using qsort function of C++.

Thanks in advance
Posted

You don't need to copy the vector to the int* buffer. STL provides the sort function, see the documentation page[^] for a code sample.
 
Share this answer
 
Question: is that the only way data is inserted to this buffer? If yes, then that means the buffer is already sorted before insertion! If that is the case, you only need to find the correct insert position and insert your new value there. See http://www.cplusplus.com/reference/stl/vector/insert/[^]
 
Share this answer
 
STL set or priority_queue can be used so that the container will be in sorted order even if the data inserted are in random order. So if we use set/priority_queue, no need to call sort explicitly
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900