Reputation: 25
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef vector<pair<double, double> > Vec; //cords vector (0.0,0.0)/(x,y)
typedef pair<double, double> Punto; //single coord
int main()
{
int x;
cout << "cuants vertex?" << endl;
cin >> x;
Vec V[x]; // Declare vector of pairs as long as user wants
Punto P;
for (int i = 0; i < V.size(); i++) { //fill vector with coords
cout << "Introdueix coordenada numero: " << i;
cout << "x: ";
cin >> P.first;
cout << "y: ";
cin >> P.second;
V.push_back(P);
}
for (int c = 0; c < V.size(); c++) { //show all coords
P.first = V[c].first;
P.second = V[c].second;
cout << P.first << P.second << endl;
}
}
This is a simple code filling a vector<pair<double,double>>
, it gives this errors:
main.cpp: In function ‘int main()’:
main.cpp:16:18: error: request for member ‘size’ in ‘V’, which is of non-class type ‘Vec [x] {aka std::vector > [x]}’
for(int i=0;i<V.size(); i++){
^~~~
main.cpp:19:5: error: request for member ‘push_back’ in ‘V’, which is of non-class type ‘Vec [x] {aka std::vector > [x]}’
V.push_back(P);
^~~~~~~~~
main.cpp:21:19: error: request for member ‘size’ in ‘V’, which is of non-class type ‘Vec [x] {aka std::vector > [x]}’
for(int c=0; c<V.size(); c++){
^~~~
main.cpp:22:16: error: ‘Vec {aka class std::vector >}’ has no member named ‘first’
P.first=V[c].first;
^~~~~
main.cpp:23:17: error: ‘Vec {aka class std::vector >}’ has no member named ‘second’; did you mean ‘end’?
P.second=V[c].second;
^~~~~~
Any way to solve it?
Upvotes: 1
Views: 1085
Reputation: 20579
Vec V[x];
x
is not a constant expression, so you are declaring a variable-length array. This is a compiler extension and is not C++. And an array cannot have .size()
member.
You need to change it to:
Vec V;
(Also, use Vec::size_type
to go through the vector, or you will get a signedness warning.)
Upvotes: 1
Reputation: 16593
This line:
Vec V[x]; // Declare vector of pairs as long as user wants
Is actually creating a C-style array of Vec
, not a single Vec
. You should use round parentheses instead, constructing a single Vec
:
Vec V(x); // Declare vector of pairs as long as user wants
However, now push_back
will add additional elements. Replace
V.push_back(P);
with
V[i] = P;
Upvotes: 5