0

I am practicing inserting and shifting arrays, I have a Contacts program and currently trying to write a function for adding a contact and inserting that contact in the correct position based on their last name

Note: I do not need to do any checks, checks are all done previously before reaching this function, simply insert and shift.


The structure I'm working with:

struct contact{
    char firstName[MAXCHAR];
    char lastName[MAXCHAR];
    char phoneNum[MAXCHAR];
    char email[MAXCHAR];
    Group group;
};

My Function:

void addContact(contact contacts[],int &numContacts, contact &aContact) {
  int index = 0;
  int insertIndex = numContacts;
  
  for (int i = 0; i < numContacts; i++){
    if(aContact.lastName < contacts[i].lastName){
        insertIndex = i;
        break;
    }
  }
  for (int index = numContacts; index > insertIndex; --index) {
    contacts[index] = contacts[index - 1];
  }
  contacts[insertIndex] = aContact;
  numContacts++;
}

aContact is the contact to be added.

numContacts is thee number of contacts currently

contacts[] is the array that needs to be inserted into.

Let's say, contacts[] currently has 3 elements from top down :

Ahmed;Asaf;971-111-9999;asafa@gmail.com;3
Alex;Smith;503-222-4444;alex.smith@gmail.com;0
Anna;White;503-222-1111;annaw@gmail.com;1

and aContacts has:

Rekha;Kaur;503-111-2222;kaurr@gmail.com;2

I would like aContacts to be inserted into the contacts[] by the last name.

Ahmed;Asaf;971-111-9999;asafa@gmail.com;3
Rekha;Kaur;503-111-2222;kaurr@gmail.com;2
Alex;Smith;503-222-4444;alex.smith@gmail.com;0
Anna;White;503-222-1111;annaw@gmail.com;1
Valkonaan
  • 1
  • 1
  • 1
    That is not how you compare native string buffers in C++ (or C, for that matter). Either use `std::string` for your members, or correctly use [`strcmp`](https://en.cppreference.com/w/c/string/byte/strcmp) if you still want to use native char[] strings. Fwiw, this can be done considerably more search-efficient using a combination of [`std::upper_bound`](https://en.cppreference.com/w/%20%20cpp/algorithm/upper_bound) and [`std::rotate`](https://en.cppreference.com/w/cpp/algorithm/rotate), provided the present list is already sorted at the time you call `addContact`. – WhozCraig Oct 08 '22 at 07:23

0 Answers0