-1

I am trying to make a vector that stores cities and their time zones.

I have declared the class City and I want to output the cityName of every City in the vector.

#include <iostream>
#include <string>
#include <vector>
#include <cmath>

class City
{
    public:
        string cityName;
        char countryIso1;
        char countryIso2;
        int offset;
        City(string aCityName, char aCountryIso1, char aCountryIso2, int aOffset) {
            cityName = aCityName;
            countryIso1 = aCountryIso1;
            countryIso2 = aCountryIso2;
            offset = aOffset;
        }
};



vector<City> cities = {
    {"Abidjan", 'C', 'I', 0},
    {"Lagos", 'N', 'G', 60}
};

/* ---------- MAIN ---------- */
int main() {
    for (int i = 0; i < cities.size(); i++)
    {
        cout << cities[i].cityName << endl;
    }
    
    return 0;
}

The error I got in the terminal:

error: non-aggregate type 'vector<City>' cannot be initialized
      with an initializer list
vector<City> cities = {
             ^        ~
Chang Yao Liu
  • 39
  • 1
  • 7

2 Answers2

5

sizeof(cities) is incorrect. That's returning the size of the data your entire array occupies, not the the amount of elements in your array. Change it to sizeof(cities) / sizeof(cities[0])

More info here

Edited to add the correction:

int main() {
    for (int i = 0; i < sizeof(cities) / sizeof(cities[0]); i++)
    {
        cout << cities[i].cityName << endl;
    }
    
    return 0;
}
Andy
  • 12,859
  • 5
  • 41
  • 56
1

In C++, it's always better to use vector or array container over raw arrays:

This is how I would use an Array container:

std::array<City,3> arr_of_cities;

This is how I would use a Vector container:

std::vector<City> vec_of_cities;

Adding elements:

vec_of_container.push_back(<City object>);

Accessing elements:

vec_of_containers.at(<index>);  
or  
vec_of_container[<index>]; //the first one is better though 

(Same for array container)

kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
  • 1
    In a perfect C++ world, this answer is the route you want to go with. You want to stay way from basic arrays and use the STL as much as possible. It's cleaner and easier to read. – Andy Aug 01 '20 at 04:20