c++ - 从 C++ 中的 int 方法返回一个数组
问题描述
我正在为具有两个函数的多维数组编写代码。
第一个函数(read()
)获取每个数组的值,第二个函数显示每个数组。
我的问题是从读取函数返回得到的数组。
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <time.h>
#include<cassert>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
using namespace std;
typedef int Sec[2][2];
int read(Sec sec){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cin>>sec[i][j];
}
}
return sec;
}
void sho(){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cout<<sec[i][j];
}
}
}
int main() {
read(Sec sec);
sho(sec);
}
解决方案
试试这种方式:
#include <iostream>
//you dont need ctime here
#include <ctime>
//you dont need csdtlib here
#include <cstdlib>
//you dont need cmath here
#include <cmath>
//you dont need time.h here
#include <time.h>
//you dont need cassert here
#include<cassert>
/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
using namespace std;
typedef int Sec[2][2];
//by adding the "&" symbol you give the function read a refrenze to a variable of
//type sec, which allows to change the values, it is like a derefrenzed pointer
void read(Sec& sec){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cin>>sec[i][j];
}
}
}
//you dont need a refrenze here, because u just want to read from the Sec object, if
//you want to run a bit faster you couldnt use:
//void show(const Sec& sec),
//this would give the function show a refrenze you cant edit, so perfectly for
//reading values
void show(Sec sec){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
cout<<sec[i][j];
}
}
}
int main() {
Sec sec;
read(sec);
show(sec)
}
推荐阅读
- go - 将密码从 []byte 转换为 string 时 go package wincred 添加空格
- java - Pattern.matcher() 究竟是如何工作的?
- ruby-on-rails - Rails - 将数据库信息更改为环境变量时出现迁移错误 - AWS
- javascript - 如何将 ES6 JSON 对象转换为字典?
- node.js - 为什么自制程序在链接仅桶装公式时要求我添加 --force 选项?
- java - 如何在使用 JavaComm lib 从计算机(调制解调器)拨号到手机时获得音频通量
- javascript - 如何修复我的 js 绑定实现?
- html - 将无序列表与不同数量的列表项对齐
- traefik - 使用 Traefik 的简单 http 反向代理总是产生 404
- git - Git:如何检索不再在本地计算机上的分支?