Home > Software engineering >  CS50 - PSET3 Run off - trouble understanding the vote function, more specifically what preferences[v
CS50 - PSET3 Run off - trouble understanding the vote function, more specifically what preferences[v

Time:11-09

Im currently doing cs50 and on pset3, i came across this tough problem set Runoff So basically, this is a solution for vote() function that searches for a specific candidate and returns true and records the votes if the candidate is found using a runoff-style election where voters are given preferences in order of ranks, the two-dimensional array preferences has already been initialized. Candidates is another array with a list of candidates

// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
    
    
    for (int i = 0; i < candidate_count; i  ){
        if (strcmp(candidates[i].name,name)==0){
            preferences[voter][rank] = i;
            return true;
        }
    }

just that i'm really confused as to what

preferences[voter][rank] = i;

does when such a candidate is found/true. What does it mean by = i; everytime the loop runs? Why not preferences[voter][rank]=candidates[i];

been struggling with this as I cant really get my head around it, any help would be really appreciated. thank you.

CodePudding user response:

What does it mean by = i;

It stores the index (read: position) of the candidate in its respective candidates array. Later on, you can look up the candidate's name by using this index.

Why not preferences[voter][rank]=candidates[i];

Because (I assume) preferences is a 2-dimensional int (or so) array. Of course, you could use a different type of an array and store (for example) a pointer to the candidate as well.

  • Related