[英]Input elements of structure in C++
I'm trying to implement a structure in C++ 14. I have made a structure that has 3 int
values 我正在尝试在C ++ 14中实现一个结构。我已经建立了一个具有3个
int
值的结构
struct mystruct{
int a;
int b;
int c;
};
In my main function, I'm initializing a structure array in the following way: 在我的main函数中,我用以下方式初始化结构数组:
int main(){
mystruct X[] = {{1,2,3}, {4,5,6}};
.
.
}
I'll pass this array to a function where I'll perform some operations on it. 我将把这个数组传递给一个函数,我将对它执行一些操作。 That function could be like:
那个功能可能是这样的:
int myfunc(mystruct X[]){
//do something
}
How can I take the values for this array as user input using cin
, instead of hardcoding them (perhaps using objects)? 如何使用
cin
将此数组的值作为用户输入,而不是对它们进行硬编码(可能使用对象)? I'm not sure how to go about this. 我不知道该如何解决这个问题。
Edit: I was hoping this could somehow be achieved using objects 编辑:我希望这可以以某种方式使用对象实现
You could implement an input operator for your struct
. 您可以为
struct
实现输入运算符。 Something like this would work: 像这样的东西会起作用:
std::istream& operator>>(std::istream& is, mystruct& st)
{
return is >> st.a >> st.b >> st.c;
}
Now you can read in from a mystruct
like this: 现在你可以从这样的
mystruct
读入:
mystruct t;
std::cin >> t;
(Note that the function above doesn't handle errors) (注意上面的函数不处理错误)
Now adding these new structs to an array could be done very simply through the use of a loop. 现在,通过使用循环可以非常简单地将这些新结构添加到数组中。 (I would recommend the use of
std::vector
here). (我建议在这里使用
std::vector
)。
Here is an example that uses std::vector
: 这是一个使用
std::vector
的例子:
std::vector<mystruct> arr;
for (mystruct t; std::cin >> t;)
{
arr.push_back(t);
}
myfunc(arr.data()); // Or you could change the signature of the
// function to accept a vector
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.