如何使用 for 循环C++将不同的值输入到 2D 指针到指针数组中
How to input different values into a 2D pointer-to-pointer array using a for loop C++
我创建了两个数组,friends和timechat。与其编写手动将每条数据放入 2d 数组的长代码,不如使用 for 循环来完成。我创建了一个 2D 数组,2 列和 5 行。一列必须包含另一列的所有朋友的名字。我哪里出错了?
法典:
string **friendslist;
friendslist = new string*[10];
for (int i = 0; i < 10; i++)
friendslist[i] = new string[10];
string friends[5] = {"Bob","Rob","Jim","Hannah","James"};
string timechat[5] = {"12:00", "5:00", "22:00", "18:30", "11:45"};
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
{
friendslist[j][i] = friends[i];
cout << friendslist[j][i] << " ";
}
cout << endl;
}
cin.get();
我已经删除了所有内容,并将其放在推荐的新手风格中,并带有额外的显式变量名称......在这个阶段对你来说非常重要的东西。我故意忽略了你的timechat
所以你可以先掌握数组机制和循环。关于更好地利用std::
库与arrays
、vectors
和maps
的建议很好,但应该稍后再说。首先要理解这一点,以及它与你的不同之处/不同之处:
#include <iostream>
#include <string>
using namespace std;
const int NUMBER_OF_LISTS_OF_FRIENDS = 2;
const int NUMBER_OF_FRIENDS_IN_ONE_LIST = 5;
int main(int argc, const char *argv[]) {
// put your constant data at top
string friends[NUMBER_OF_FRIENDS_IN_ONE_LIST] = {"Bob","Rob","Jim","Hannah","James"};
string **friendslist;
friendslist = new string*[NUMBER_OF_LISTS_OF_FRIENDS]; // Two lists of friends
// Allocate your storage
for (int init_list_index = 0; init_list_index < NUMBER_OF_LISTS_OF_FRIENDS; init_list_index++) {
// each friend list is of length 5
friendslist[init_list_index] = new string[NUMBER_OF_FRIENDS_IN_ONE_LIST];
}
// Initialize the storage with useful contents
for ( int list_index = 0; list_index < NUMBER_OF_LISTS_OF_FRIENDS; list_index++ ) {
for (int friend_index = 0; friend_index < NUMBER_OF_FRIENDS_IN_ONE_LIST; friend_index++ ) {
friendslist[list_index][friend_index] = friends[friend_index];
}
}
// output all the values in a clear format as an initialization check
for ( int list_index = 0; list_index < NUMBER_OF_LISTS_OF_FRIENDS; list_index++ ) {
for (int friend_index = 0; friend_index < NUMBER_OF_FRIENDS_IN_ONE_LIST; friend_index++ ) {
cout << "list " << list_index << ", friend index " << friend_index << ": "
<< friendslist[list_index][friend_index] << "t";
}
cout << endl;
}
}
您的循环计数器没有多大意义。 例如,您使用:
for (int j = 0; j < 1; j++)
这有效地迭代一次,j == 0
. 此外,您还有一个嵌套循环:
for (int y = 0; y < 1; y++)
这再次迭代一次,但您甚至没有引用y
相关文章:
- 用户定义函数中的指针和输入
- 检查输入 std::array 指针数据是否等于某个常量数组
- 使用终止程序的指针在数组中输入字符串
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 如果将两个相同的指针作为输入传递,memcmp 会做什么?
- 我可以更改将引用参数传递到指针中并使其正常工作的函数的输入(C、C++)吗?
- STD :: Atomic_fetch为什么将指针作为其输入参数
- 如何使用指针将用户输入存储到向量中
- 是否可以从标准输入指向指针的地址
- C 中的动态数组(用指针表示) - 输入元素
- 通过用户输入到对象的指针的C 向量
- C++ ->尝试逐字阅读一行文本。如何使指针等效于用于存储输入的当前二维数组
- 如何为作为雇员类的指针传入的构造函数输入数据
- C 函数通过指针通过参考与参数输入参数
- 如何仅将数字值存储在给定输入文件中的2D数组中?(没有指针)
- 在C++中,是否可以将任意指针作为输入参数
- 访问C 类中功能指针数组的输入
- 数组和指针输入
- 如何使用python将指针输入发送到c++程序
- 如何通过指针输入整数数组并打印出数组和数组的大小(C++)