ColinO
ColinO

Reputation: 59

Using an iterator to sort a vector by comparison

I've created a vector of a class called albums and as I add a new album to the vector i'm first trying to compare the album title to the first index of the vector and sort it in alphabetical order. Here is my code:

vector<album> cd;                //declared in main

void add_cd_vector(vector<album>& cd)
{
    string name;
    int barcode;


    cout << "Enter the album name: ";
    cin >> name;
    cout << "Enter the barcode: ";
    cin >> barcode;
    album newCD(name, barcode);       //constructor function for class

    if(cd.size() == 0) //no vector created yet
    {
         cd.push_back(newcd);
    }
    else{
         vector<album>::iterator it;
         for(it = cd.begin(); it!=cd.end(); it++)
         {
              if(name < it.get_name())    //getter function for name in  class
              {
                    cd.insert(it, newCD);     //should insert into the vector
              }
          }
    }

My problem lies either within my if statement or the command inside of it, i'm not sure the proper syntax.

Upvotes: 0

Views: 46

Answers (1)

Anon Mail
Anon Mail

Reputation: 4770

I think you want to change your insert logic to this:

for(it = cd.begin(); it!=cd.end(); it++)
{
    if (name < it->get_name())
    {
        break;
    }
}
cd.insert(it, newCD);

This way, the element gets inserted even if it's greater than the last element. Note that with this logic you need not check if the vector is empty so the code is simpler.

Upvotes: 3

Related Questions