用C++输入结构元素

dec*_*kor 2 c++ arrays structure c++14

我正在尝试在C++ 14中实现一个结构.我已经创建了一个具有3个int值的结构

struct mystruct{
    int a;
    int b;
    int c;
};
Run Code Online (Sandbox Code Playgroud)

在我的main函数中,我用以下方式初始化结构数组:

int main(){
    mystruct X[] = {{1,2,3}, {4,5,6}};
    .
    .
}
Run Code Online (Sandbox Code Playgroud)

我将把这个数组传递给一个函数,我将对它执行一些操作.这个功能可能是这样的:

int myfunc(mystruct X[]){
    //do something
}
Run Code Online (Sandbox Code Playgroud)

如何将此数组的值作为用户输入使用cin,而不是对它们进行硬编码(可能使用对象)?我不知道该如何解决这个问题.

编辑:我希望这可以以某种方式使用对象实现

Arn*_*rah 7

您可以为您实现输入操作符struct.像这样的东西会起作用:

std::istream& operator>>(std::istream& is, mystruct& st)
{
    return is >> st.a >> st.b >> st.c;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以从mystruct这样的内容读入:

mystruct t;
std::cin >> t;
Run Code Online (Sandbox Code Playgroud)

(注意上面的函数不处理错误)

现在,通过使用循环可以非常简单地将这些新结构添加到数组中.(我建议在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
Run Code Online (Sandbox Code Playgroud)