#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;
}
}
这是一个填充vector<pair<double,double>>
的简单代码,它给出了这个错误:
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;
^~~~~~
有什么方法可以解决吗?
这一行:
Vec V[x]; // Declare vector of pairs as long as user wants
实际上是在创建一个C风格的Vec
数组,而不是单个Vec
。您应该改用圆括号,构造单个Vec
:
Vec V(x); // Declare vector of pairs as long as user wants
但是,现在push_back
将添加其他元素。取代
V.push_back(P);
跟
V[i] = P;
Vec V[x];
x
不是常量表达式,因此您声明的是可变长度数组。 这是一个编译器扩展,不是C++。 数组不能有.size()
成员。
您需要将其更改为:
Vec V;
(此外,使用 Vec::size_type
遍历向量,否则您将收到签名警告。