简体   繁体   中英

How to insert value into c++ boost::multiindex collection at specific index like in std::list

In boost::multi_index I try to insert value at specific location, how ever I did not find any example how to accomplish this task in boost documentation https://www.boost.org/doc/libs/1_59_0/libs/multi_index/doc/tutorial/indices.html or elsewhere.

This is a code which allows to insert at the beginning or the end of the collection.

struct animal {
    std::string name;
    int legs;
};

typedef multi_index_container<
        animal,
        indexed_by<
                sequenced<>,
                ordered_non_unique<member<animal, std::string, &animal::name>>,
                ordered_non_unique<member<animal, int, &animal::legs>>,
                random_access<>
        >
> animal_multi;

int main() {
    animal_multi animals;

    animals.push_back({"shark", 0});
    animals.push_back({"spider", 8});
    animals.push_front({"dog", 4});

    auto it = animals.begin();
    auto end = animals.end();
    for (; it != end; ++it)
        std::cout << it->name + " ";

    return 0;
}

Current output is: dog shark spider

How can I adjust the code in order to pass something, for example, between shark and spider?

What you can do is the following

//...
auto it = animals.begin();
animals.emplace(++(++it), animal{"elephant", 4});
//...

Note ++it as random_access<> gives you additional operator[] and at() for positional access to the elements but does not provide the iterator with an operator+= as far as I can tell. That means you will have to traverse the container in order to find the spot where you need to insert an element.

According to the documentation, random access indices have several disadvantages with respect to std::vector :

They do not provide memory contiguity, a property of std::vectors by which elements are stored adjacent to one another in a single block of memory.

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