如何使用for循环C ++将不同的值输入到2D指针到指针数组中

时间:2015-03-08 18:18:28

标签: c++ arrays pointers multidimensional-array pointer-to-pointer

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

2 个答案:

答案 0 :(得分:1)

我已经对所有内容进行了解码,并将其置于具有超显式变量名称的推荐新手风格中......在此阶段对您来说非常重要。我故意忽略了你的timechat,所以你可以先掌握数组机制和循环。有关使用std::arraysvectors更好地利用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;
  }
}

答案 1 :(得分:0)

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

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

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

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

这再次迭代一次,但你甚至不参考y