一个2D数组,并按行存储值。第一个循环用于行索引,第二个循环用于列索引

时间:2019-11-22 21:28:42

标签: c++

我刚开始使用c ++

这是2D数组并按行存储值的代码。第一个循环用于行索引,第二个循环用于列索引,另外我在arr [x] [y]和arr [col]中也遇到了错误

#include <iostream>
using namespace std;

int main()
{
    int x, y;
    int arr[x][y];
    cout << "Enter row number and column number :";
    cin >> x >> y;

    int row, col;
    cout << "Enter value of array\n";

    for (int row = 0; row < x; ++row)
    {
        for (int col = 0; col < y; ++col)
        {
            cin >> arr[row][col] << " ";
        }
    }

    cout << "Value of array are:\n";
    for (row = 0; row < x; row++)
    {
        for (col = 0; col < y; col++)
        {
            cout << arr[row] << arr[col] << " ";
        }
        cout << "\n";
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

问题1:订购事宜。

int x, y; // x and y have undefined values
int arr[x][y]; // attempts to dimension an array with undefined values.
cout << "Enter row number and column number :";
cin >> x >> y; // now we have x and y values. 

解决方案:

int x, y; // x and y have undefined values
cout << "Enter row number and column number :";
cin >> x >> y; // now we have x and y values. 
int arr[x][y]; // can now dimension array

问题2:非标准代码

在标准C ++中,数组只能使用常量值标注尺寸

int arr[x][y]; // fails on many compilers. 
               // Don't be angry, they are following the language rules.

There are many reasons for this。在我看来,最大的困难是它们难以控制程序使用的自动内存量。为xy输入2000,然后观察程序失败in interesting and often bizarre ways

解决方案:

Use a std::vector here

vector<vector<int>> arr(x, vector<int>(y));

注意:

vector中的

vector个由于spatial locality低而导致性能不佳。每个vector都有自己的存储块,位于动态内存中的某个位置,并且每次程序从一个vector移到另一个vector时,都必须查找并加载新的vector数据。

如果这是一个问题,请使用单个cin >> arr[row][col] << " "; 方法like the one described here

问题3:写入输入流

cin

arr[row][col] and then attempts to write读入to the stream.”“ >> cin`仅用于输入,无法写入。

解决方案:

由于您可能根本不需要此写入,因此cin >> arr[row][col]; 根据空格分隔自动分离标记,因此我们可以放心地放弃写入。

cout << arr[row] << arr[col] << " ";

问题4:写入数组而不是数组中的数据

arr[row]

cout写入数组中的一行,而不是将单个数据值写入arr[col]。然后,它将数组中的另一行cout写入arr[row][col]

解决方案:

要在cout << arr[row][col] << " "; 处写入值,我们需要照字面做

import smtplib

# Send email to my personal email address
def send_email(subject, msg):
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login('e******@gmail.com', 'S****')
        message = 'Subject: {}\n\n{}'.format(subject, msg)
        server.sendmail('e*@gmail.com', 'e*@gmail.com', message)
        server.quit()
        print("Success: Email sent!")
    except:
        print("Email failed to send.")

我认为可以解决这个问题。

推荐阅读

Why is "using namespace std;" considered bad practice?

A good C++ reference text。您目前从中学到的东西对您没有任何帮助。

相关问题