Home > Back-end >  Building red-black tree with vector of lists in C
Building red-black tree with vector of lists in C

Time:10-28

 vector<list<Nodo<string>*>> lista;

i have this vector of lists and I'm trying to write a method to insert elements into it

  template <typename T> void HashRBT<T>:: riempimento()
{
     for(auto &it:vett_dati) 
    {   int key=it.first;
        string value=(it.second);
        int id=hashFunctionDivsion(key); 
        Nodo<T> *x=rb->searchNodo(rb->getRoot(),id);
        if(x==rb->getNillT()) 
        {
         rb->insertNodoRB(id,value);
        }

      else {  
        lista.resize(getDim());
        Nodo<T> *y= new Nodo<T>(id,value);
       lista.at(id).push_front(y); //inserimento in testa
      }
    }
    Print_Lista(); 
}

now in the else block is where I go to insert the elements in this vector of lists but I don't understand why if I comment the resize statement this doesn't work and I get an error like this: vector :: _ M_range_check. I would like someone to explain to me what happens in memory? what am i allocating with that resize?

CodePudding user response:

Break the problem down and look at it without the logic of your rb tree.

std::vector<int> vec{10,20}; // vector of size 2
vec.at(0); // fine: element 0 exists.
vec.at(1); // fine: element 1 exists.
vec.at(2); // will throw because vector has size 2, so only elements 0 and 1
vec.resize(3); // now vector has size 3: elements 0, 1, 2
vec.at(2); // fine: element 2 exists.

Whether you store an int or a std::list<Node<T>> in it doesn't matter for std::vector's fundamental logic.

So, if you access an element with std::vector::at that doesn't exist you will get an error:

std::out_of_range if !(pos < size()).

Similarly, std::vector::operator[] will not work but fail silently. Omitting the check has performance benefits.

Unlike std::map::operator[], this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior.

  • Related