gpt4 book ai didi

c++ - 如何使用for循环C++将不同的值输入到二维指针到指针数组中

转载 作者:行者123 更新时间:2023-11-28 06:23:31 27 4
gpt4 key购买 nike

我创建了两个数组,friends 和 timechat。我不想编写手动将每条数据放入二维数组的长代码,而是想用 for 循环来完成。我创建了一个二维数组,2 列和 5 行。一栏必须有其他时间的所有 friend 的名字。我哪里错了?

代码:

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:: 库与 arraysvectorsmaps 的建议很好,但应该会出现之后。首先理解这一点,以及为什么/如何与您的不同:

#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;
}
}

关于c++ - 如何使用for循环C++将不同的值输入到二维指针到指针数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930147/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com