initialization of a vector

Hello, I have an error I think with the initialization of a vector
error: no matching function for call to ‘City::City()’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
The constructor for City class take two parameters

thanks


1
2
  int numCities = 100;
  vector <City> cities(numCities);
Seems like City does not have a default constructor (i.e. a constructor that takes no arguments).
the phrase "The constructor for City class take two parameters" is mine not part of the error message
So what constructor arguments do you want to use when constructing these 100 cities?
Answering to Peter87’s question will increase your chances to get a good answer, but in the meanwhile...

Assuming you have a code like this (which doesn’t compile):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>


class City {
public:
    int first {};
    int second {};

    // City() = default;
    City(int first_arg, int second_arg);

private:
};


City::City(int first_arg, int second_arg)
    : first { first_arg }
    , second { second_arg }
{
}


int main()
{
    constexpr int Num_Cities { 100 };
    std::vector<City> cities(Num_Cities);
}


There are at least two workarounds:
1) Reserve space by std::vector::reserve() instead of the overloaded std::vector(size_type count, const Allocator& alloc = Allocator()) constructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>


class City {
public:
    int first {};
    int second {};

    // City() = default;
    City(int first_arg, int second_arg);

private:
};


City::City(int first_arg, int second_arg)
    : first { first_arg }
    , second { second_arg }
{
}


int main()
{
    constexpr int Num_Cities { 100 };
    std::vector<City> cities;
    cities.reserve(Num_Cities);
}


2) Add a suitable no-argument constructor to class City:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>


class City {
public:
    int first {};
    int second {};

    City() = default;
    City(int first_arg, int second_arg);

private:
};


City::City(int first_arg, int second_arg)
    : first { first_arg }
    , second { second_arg }
{
}


int main()
{
    constexpr int Num_Cities { 100 };
    std::vector<City> cities(Num_Cities);
}

Last edited on
std::vector::reserve() like Enoizat mentioned is probably what you want to be doing but you can also do this if you want all members of the vector to be constructed with the same two constructor arguments:

std::vector<City> cities ( /*Number of cities here*/, City{ /*arg1*/, /*arg2*/ } );
Note that reserve doesn't actually change the size of the vector so you still have to insert the cities using something like push_back.
Topic archived. No new replies allowed.