0

我创建了两个数组,朋友和时间聊天。我不想编写手动将每条数据放入二维数组的长代码,而是想用 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();
4

2 回答 2

1

我已经对所有内容进行了去乱码,并将其置于推荐的新手风格中,并带有额外显式的变量名......在这个阶段对你来说非常重要。我故意忽略了你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;
  }
}
于 2015-03-08T18:39:26.680 回答
0

您的循环计数器没有多大意义。例如,您使用:

for (int j = 0; j < 1; j++)

这有效地迭代一次,使用j == 0. 此外,您还有一个嵌套循环:

for (int y = 0; y < 1; y++)

这再次迭代一次,但你甚至不引用y

于 2015-03-08T18:24:33.363 回答