I want to create vector which stores pointers to lists as shown in image. I don't know how many lists will be needed here. So, I want to write function like this
vector<node*> address; //node is class.
if ((int)address.size()<number) //number is integer taken as input to function.
{ while((int)address.size()!=number)
{address.push(/*here I want some function which will generate
empty list and return pointer to head node or any information
that will help to access list later*/)
}
else
{ address[number-1].push_back(name); //name has type string;
//this line may be wrong for syntax but idea is A[i] gives me
// list where I want to put name.
}
Preferably using STL library.
If you want to use STL library, then just use
std::vector<std::list<node>> address; //node is class (note that you can pass size here)
// Using your code in your code:
if ((int)address.size() < number) //number is integer taken as input to function.
{
address.resize(number);
}
else
{ address.back().push_back(name); //name has type string;
}
Please note that the node
is type of the elements you want to push into the vector. As @john said, if you want to keep a list of strings then declare address
as:
std::vector<std::list<std::string>> address;
Also, if you get errors because of >>
, either compile this as C++11, or write address
as:
std::vector<std::list<std::string> > address;
It is not much clear, but I guess you want an automatic resize container (as javascript vectors) where lists indexes are 1 based (ie no list at address 0) and a method to insert at the end of one list at a given index. Basically something as 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);
}
};
Anything else you might want from such container is likely to be already implemented in the vector
and list
template classes (check stl documentation to see whats 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 suggestions:
deque
instead of a vector
, or provide a proper size hint with reserve
, otherwise you might be find yourself wondering why sometimes adding a single string in a list that does not exists yet is so slow. index - 1
with index
in the example above) and do your math on application logic)
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.