Vector pairs in C++
Hello, I need a vector, each element of which stores a pair of integers.Here is my code:
vector <pair<int,int> > g[2000];
for (int i = 0; i < m; ++i){
int a,b;
cin >> a >> b ;
g.push_back(make_pair(a,b));
}
I get the error: request for member "push_back" in "g" which is of non-class type " std::vector > 2000". Please tell me, what is my mistake?
2 answers
Actually quite informative message: you created array (for 2000 elements) of vectors.
I describe in more detail: vector is a template, but for simplicity we will assume that this is a class. If we create an object of the class, we need to write
Class class(/*params*/);
If a class has a constructor without parameters, then ()
can be omitted, for example::
Class class;
When you write
Class class[10];
Then the compiler understands this how to create an array of 10 objects of the class Class
with the default constructor (without parameters). If there is no constructor without parameters, a compilation error will occur. Example:
class C{
public: C(int a){};
//C(){};
};
int main() {
C a[5];
return 0;
}
Y array there is no method push_back
which leads to a compilation error.
I do not know what exactly you want, so either write
g[0].push_back(make_pair(a,b));
Or declare
vector <pair<int,int> > g;
Or, if size is important to you, use something like
vector <pair<int,int> > g;
...
g.resize(2000); //g.reserve(2000);
You can try it like this:
vector <pair<int, int> > g;
for (int i = 0; i < 10; ++i) {
int a = 0;
int b = 0;
cin >> a >> b;
g.push_back(make_pair(a, b));
}