Efficient data structure for storing a structural variable with the ability to sort

I have a structure

struct dbdetails
{
    int id;
    string val;
};

I need a C ++ data structure that can contain a sortable structural variable. Is it possible? I was looking at a vector that might contain a structural variable, but I will not sort it based on id, because it is a member of the structure. Any suggestions?

+5
source share
6 answers

You need a custom functor to compare your attempts. 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 further questions. Do you have a Stroustrup book?

Edit: Matteo's suggestion:

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());
...
+6

std::map. , :

std::map<int, std::string> myStuff;

int std::string . , , .

, struct . struct (, - ), map struct .

+4

vector struct, :

std::sort(vectStruct.begin(), vectStruct.end(), &vectStructSort);

bool vectStructSort(Try const& lhs, Try const& rhs) { // try is keyword.
    return lhs.id < rhs.id;
}
+1

, . ( Stl, Set - Key). Hash .

, , , , , .

+1

(std::set, std::map, std::multiset, std::multimap) . (std::list, std::vector, std::deque) , a std::sort (vector, deque) - ().

, . , , . , , , , . , sort.

, . , , .

+1

You can sort the vector based on the elements of the structure. You just need a custom comparator.

0
source

All Articles