Search code examples
c++vectorindexingelement

c++: How can I print vector elements' indexes every time I print the vector?


So, I have a vector of boats. I need to access these boats and modify them (i.e. delete them) regularly, so it would be really nice if I could print their index along with all their other information, but I can't seem to figure out how.

The closest I got to it was with a simple for loop, but that eventually prints the current index along with the previous ones, as the vector size grows (since my i was < vector.size())

vector <Boat> berths_reg; 

//print vector elements info
void Boat::print_info()
{
    cout << endl;
    for(int i = 0; i < berths_reg.size(); i++)
    {
        cout << "Index       : " << i << endl;
    }
    cout << "Boat type   : " << type << endl;
    cout << "Boat length : " << length << endl;
    cout << "Draft depth : " << draft << endl;
    cout << endl;
}

//iterate through vector to print all elements
void print_vector() 
{
    vector <Boat> ::iterator it;

    for (it = berths_reg.begin(); it != berths_reg.end(); ++it)
    {
        it->print_info();
    }
}

//Storing boats (objects data) inside vector
void add_boat(Boat* b, string type, int length, int draft)
{
    b->get_type(type);
    b->get_length(length);
    b->get_draft(draft);
    berths_reg.push_back(*b);
}

Solution

  • Simply print both the index and the info within the same loop:

    void print_vector() 
    {
      for(int i = 0; i < berths_reg.size(); ++i)
      {
        cout << "Index       : " << i << endl;
        berths_reg[i].print_info();    
      }
    }