[英]How can I create a vector from struct in main?
What am I doing wrong here?我在这里做错了什么? I'm trying to make a vector from struct in main but it keep showing error.
我正在尝试从 main 中的 struct 创建一个向量,但它一直显示错误。
#include <iostream>
#include <vector>
using namespace std;
struct A{
int y;
};
int main()
{
int x;
cin >> x;
vector<A> vertex;
for(int i = 0; i < x; i++){
vertex.push_back(x)
cout << vertex[i]<<endl;
}
return 0;
}
x is an int not an A x 是 int 不是 A
you need你需要
int main()
{
int x;
cin >> x;
vector<A> vertex;
for (int i = 0; i < x; i++) {
A a;
a.y = x;
vertex.push_back(a);
cout << vertex[i].y << endl;
}
}
you can make your original code work by providing an implicit conversion from int to A您可以通过提供从 int 到 A 的隐式转换来使您的原始代码工作
also you would need to provide a << operator for A您还需要为 A 提供 << 运算符
You are trying to push_back()
an int
into a vector
that holds A
objects.您正在尝试
push_back()
将int
放入包含A
对象的vector
中。 You have not defined any conversion from int
to A
, hence the error.您尚未定义从
int
到A
任何转换,因此出现错误。
You can add a constructor to A
that takes in an int
and assigns it to y
:您可以向
A
添加一个构造函数,该构造函数接受一个int
并将其分配给y
:
struct A{
int y;
A(int value) : y(value) {}
};
Or, you can omit the constructor and instead create an A
object and pass it to push_back()
:或者,您可以省略构造函数,而是创建一个
A
对象并将其传递给push_back()
:
A a;
a.y = x;
vertex.push_back(a);
Or, using Aggregate Initialization :或者,使用聚合初始化:
vertex.push_back(A{x});
Or, you can alternatively use emplace_back()
instead, which will construct the A
object inside the vector
for you, using the specified parameter(s) for the construction:或者,您也可以使用
emplace_back()
代替,它将为您在vector
内构造A
对象,使用指定的参数进行构造:
vertex.emplace_back(x);
Either way, that will fix the error you are seeing.无论哪种方式,这将解决您看到的错误。
Then, you will run into a new error, because you have not defined an operator<<
for printing A
objects, so you will have to add that, too:然后,你会遇到一个新的错误,因为你没有定义一个
operator<<
来打印A
对象,所以你也必须添加它:
struct A{
int y;
...
};
std::ostream& operator<<(std::ostream &os, const A &a) {
return os << a.y;
}
Now, your code will run.现在,您的代码将运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.