简体   繁体   中英

Which data structure is best for an ordered list of strings?

I have a bunch of strings in a container. These strings have to be unique in the container, but I want to preserve the order or the strings (the order in which they were added).

Is there a more elegant solution to this than using a vector and testing before each add-operation whether the element is already in the vector, eg by using std::find from ? Because of the uniqueness, I am tempted to use a set, but then how can I preserve the order in which the strings were added to the set?

If you were to write your own container, a classical approach (see eg LinkedHashSet in Java) would be a linked list between the elements added to a tree/hashtable; this works especially well if you have control over the tree nodes (you can store the prev/next pointers directly in them).

This can be done using the STL (storing some struct like

struct Elem
{
    std::string payload;
    std::set<Elem>::iterator prev;
    std::set<Elem>::iterator next;
}

), but an easier approach could be to use a set plus a vector of iterators to the set, maybe encapsulated in some class to handle removal consistently. The set will handle the storage and the uniqueness, the vector will remember the insertion order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM