0

I have a variable declarations and a struct class as such

std::string fileName;
std::ifstream file(fileName);
passengerData data;
std::vector<passengerData> result;

struct passengerData
{
    double arrivalTime;
    int passengerClass;
    double serviceClass;
};

This data is used in main like so

 std::cout << "Please enter the name of the file: " << std::endl; 
 std::cin >> fileName;

  while (file >> data.arrivalTime >> data.passengerClass >> data.serviceClass) 
     result.push_back(data);
    
   for(passengerData i: result) {
      enqueue(i.arrivalTime); 
      std::cout << "Passenger with index " << result[i] << " has entered the queue" << std::endl;  
   }

My occur at the last line of my for loop result[i] where i get the error no operator "[]" matches these operands -- operand types are: std::vector<<error-type>, std::allocator<<error-type>>> [ passengerData ]

Im basically trying to do something like the following

Passenger 0 has entered the queue
Passenger 1 has entered the queue
Passenger 2 has entered the queue
etc....

Where 0 1 and 2 are the indexes of the records in the vector

It may also be a bit too much to ask but how may I transform this snippet into a int array rather than a vector?

ATTEMPTED FIX

 for (int i = 0; i < result.size(); i++) { 
       enqueue(i.arrivalTime);
       std::cout << "Passenger with index " << result[i] << " has entered the queue" << std::endl;  
       }
    

Recieve error expression must have class type on line enqueue(i.arrivalTime);

davidlingg2000
  • 107
  • 1
  • 5
  • 3
    Try to use a classical `for (int j = ...` loop instead of a `for range` loop – Damien Oct 01 '20 at 08:45
  • Does this answer your question? [Access index in range-for loop](https://stackoverflow.com/questions/12397532/access-index-in-range-for-loop) – Botje Oct 01 '20 at 08:46
  • @Damien see my updated question – davidlingg2000 Oct 01 '20 at 08:53
  • 1
    You can only use the square brackets for vectors with integer numbers (vector indices). In your code, `i` is not an integer but a `passengerData`. You can either use a classic for loop `for (int j = 0; j < result.size(); j++) { result[j]; }` like @Damien points out, or you can put a variable `int j = 0;` outside the loop and increment it within the loop body `j++;`. – Jorge Bellon Oct 01 '20 at 08:53
  • 1
    In your updated fix, you are trying to access a member `arrivalTime` for an integer, which does not exist. You would need to do `result[i].arrivalTime` instead. The passenger is `result[i]`, and the position/index of that passenger is `i`. If you struggle with this concept I suggest you to read a chapter about structures/data types and another about loops. – Jorge Bellon Oct 01 '20 at 08:55
  • @JorgeBellon No i do understand the concept I just forgot about it haha – davidlingg2000 Oct 01 '20 at 09:04

0 Answers0