creating an array of structs in c++

Viewed 237428

I'm trying to create an array of structs. Is the code below valid? I keep getting an expected primary-expression before '{' token error.

int main() {
  int pause;
  struct Customer {
    int uid;
    string name;
  };

  Customer customerRecords[2];
  customerRecords[0] = {25, "Bob Jones"};
  customerRecords[1] = {26, "Jim Smith"};
  cin >> pause;
  return 0;
}
5 Answers

you can use vector. First Define the Struct.

  struct Customer {
    int uid;
    string name;
  };

Then,

vector<Customer> array_of_customers;

By using vector, you will have more freedom and access in the array of structure.

Now if want to add an struct element in the define array. You can use

array_of_customer.push_pack(/* struct element here */)

Example:

Customer customer1;
customer1.uid = 01;
customer1.name = "John Doe";

Customer customer2;
customer2.uid = 02;
customer2.name = "Blah Blah";


array_of_customers.push_back(customer1);
array_of_customers.push_back(customer2);

you have now an array of struct.

Related