samedi 3 janvier 2015

run time speed of std::list::push_back()

Adding a list to an element would be of time complexity O(1), but I guess that in c++11 lists its O(n^2) (please point out if I am wrong). Could you please tell me if I could use the std::list::push_back() function if I want to run my program faster (assuming that this function will be called many times during the run time).


why I believe that the time complexity for adding an element to the list is O(1):


while browsing online, I found this:



std::list<int> a;
a.push_back(1); //initialize
a.push_back(2);
a.push_back(3);
std::list<int>::iterator i = a.begin();
std::cout<<*(++i); // displays 2
std::cout<<*(++i); // displays 3


So there should be an array of pointers each pointing to each node in the linked list. Each time we call the push_back() member function, the array of pointers should be cleared and reallocated; don't you think so? please point out giving reasons, if I am wrong because I am new to c++ (I concluded this because its obvious that we cannot extend the size of an array without destroying the original and re-initializing it).


Aucun commentaire:

Enregistrer un commentaire