I am trying to create a class that has a member variable of type std::vector<std::pair<int, int>>.
Below is an example class that recreates my original class:
class temp {
private:
vector<pair<int, int>> map;
public:
temp() {
vector<pair<int, int>> map(3, { 0, 0 });
}
void foo() {
//Do something
}
};
when I add the following line of code in the constructor of the above class, it throws no error:
cout<<map[0].first<<" "<<map[0].second<<'\n';
However, when I add the same line of code in the function foo and call it like so:
temp map{};
map.foo();
it throws the following exception:
exception thrown when the last line of code is added to foo()
What am I doing wrong?
>Solution :
In your temp constructor you define a brand new and totally separate variable with the name map.
What you should use is a constructor initializer list:
temp()
: map(3)
{
// Empty
}
The above will initialize the vector using the constructor taking a size argument. This specific example means that map will be initialized with three default-constructed elements.