This is not very clear, but I think you want a container with automatic resizing (like javascript vectors) where index lists are based on 1 (i.e. there is no list at address 0) and a method to insert at the end of one list on given index. Basically something like this:
struct MyCollection: public std::vector<std::list<std::string> > { void push_at(size_t index, const std::string& item) { resize(std::max(size(),index - 1); at(index - 1).push_back(item); } };
Everything you want from such a container is most likely already implemented in the vector
and list
template classes (check the stl documentation to see what is available), for example:
MyCollection a; //declares an empty collection a.push_at(6,"hello"); //create 6 lists and inserts "hello" at the end of the last one a[5]; //gets 6th list (method [] is 0-based on vector) a.push_at(6,"hi"); // since list already exists it just adds "hi" at the end a[5].front() //"hello" a[5].back() //"hi"
Other offers:
- if you plan to place a lot of elements there and should not have the whole list of objects at consecutive addresses (i.e. compatibility of a vector with C arrays), I suggest you use
deque
instead of vector
, or provide a hint about the correct reserve
size, otherwise you may be interested why sometimes adding one line to a list that does not yet exist is so slow. - STL uses 0-based indexes. You will only be confused by defining 1-based, so count your lists from 0 (just replace
index - 1
with index
in the above example) and do your math in the application logic)
pqnet source share