【问题标题】:How to call member of the Array? [closed]如何调用数组的成员? [关闭]
【发布时间】:2014-12-22 14:30:18
【问题描述】:

我正在尝试使数组的函数打印 3 列和 3 行的二维。我不知道的是如何让程序从用户那里获取输入并将其传递给这部分的函数:

array<array<int, columns>,rows>c[item];
cout<<"2-D Array print: "<<endl;

我一直在想办法,但我似乎无处可去:(。请我需要帮助。

#include <iostream>
#include <array>
#include <iomanip>

using namespace std;

const size_t rows=3;
const size_t columns=3;
void printArray(const array<array<int, columns>,rows>&);

int main(){
    const size_t arraysize=9;
    array<int, arraysize>c;

    cout<<"Enter an array of 9 floats: "<<endl;

    for (size_t i=0;i<c.size(); i++) {
        cin>>c[i];
    }
    cout<<endl;

    cout<<"Normal array print: ";
    for (int item :c) {
        cout<<item<<" ";
    }

    array<array<int, columns>,rows>c[item];
    cout<<"2-D Array print: "<<endl;
}

void printArray(const array<array<int, columns>,rows>&a){
    for(auto const &row:a)
    {
        for(auto const &element:row)
            cout<<element<<" ";
            cout<<endl;
    }
}

【问题讨论】:

  • 那么你的问题是什么?你得到一个编译错误?意外/不正确的行为?顺便说一句,你的代码是 C++,所以我不知道你为什么一直使用 CSS 代码 sn-p 来格式化它,那不是 C++ 代码。
  • 对不起,我是新手,我不知道如何格式化。是的,当我编译它时,我在这部分数组中出现错误 array,rows>c[item];特别是它的最后一部分,c[item];

标签: c++ arrays sorting c++11 multidimensional-array


【解决方案1】:

(由于您在打印点已经有了数据,我将问题解释为:我不知道如何转换数组以便将其传递给函数)

除了std::array 是一个连续的内存存储并且您可能会使用如下的 uberhack(不保证可以正常工作):

printArray(reinterpret_cast<const array<array<int, columns>, rows>&>(c));

如果您使用保证数据一致性的转换循环,我会感觉更安全:

array<array<int, columns>, rows> printArr;
for (int x = 0; x < rows; ++x) {
    for (int y = 0; y < columns; ++y) {
        printArr[x][y] = c[x*columns + y];
    }
}
printArray(printArr);

输出:

Enter an array of 9 integers: 

Normal array print: 1 2 3 4 5 6 7 8 9 2-D Array print: 
1 2 3 
4 5 6 
7 8 9 

Live Example

【讨论】:

  • 大声笑我们已经发布了两种不同的解决方案,不确定哪一个 OP 想要,看来我必须删除我的:D
  • 现在说还为时过早!如果帖子足够清晰,我们将只有一个:/
  • 我都试过了,它们都有效。非常感谢!如果我在未来发帖,我会尽量让我的帖子更清楚。我还在学习如何使用这个页面。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2016-03-13
  • 2017-11-22
  • 1970-01-01
相关资源
最近更新 更多