I have a structure
struct dbdetails
{
int id;
string val;
};
I need a data structure in C++ that can hold structure variable with a sort capability. Is it possible? I was looking at vector, which can hold structure variable, but I will not be able to sort it based on id, because it is a structure member. Any suggestions?
Explanation: Stack data structure is most suitable to implement redo-undo feature. This is because the stack is implemented with LIFO(last in first out) order which is equivalent to redo-undo feature i.e. the last re-do is undo first.
A dynamic array is a good choice if the accesses are random and insertion/deletion is at the end. A stack is a good choice if the accesses are always FIFO. A queue is a good choice if the accesses are always LIFO. A deque is a good choice if accesses are always at the ends.
A data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently. A data structure is not only used for organizing the data. It is also used for processing, retrieving, and storing data.
There are two data structures in the standard Java collections package that sort automatically: the interfaces SortedSet and SortedMap , which are implemented by TreeSet and TreeMap , respectively.
You need a custom functor for comparing your tries. This should do the trick:
#include <algorithm>
#include <vector>
// try is a keyword. renamed
struct sorthelper : public std::binary_function<try_, try_, bool>
{
inline bool operator()(const try_& left, const try_& right)
{ return left.id < right.id; }
};
...
std::vector<try_> v;
// fill vector
std::sort(v.begin(), v.end(), sorthelper());
...
Please feel free to ask if you have any follow-up questions. Do you possess the Stroustrup book?
Edit: Suggestion of Matteo:
struct try_
{
int id;
string val;
bool operator<(const try_& other) const
{return id < other.id;}
}; // no s here plz.
...
std::vector<try_> v;
// fill vector
std::sort(v.begin(), v.end());
...
You could use a std::map
. They are sorted by key, so you could do:
std::map<int, std::string> myStuff;
This is a map with an int
as key and std::string
as value. When you iterate over the map, you’ll find that it’s automatically sorted by the key.
Note you would no longer need your struct
with this solution. If you absolutely need the data in a struct
(perhaps to interface with some external library) you could always copy data from the map
into a struct
as needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With