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

How to input different values into a 2D pointer-to-pointer array using a for loop C++

本文关键字:指针 输入 2D 数组 for 何使用 循环 C++      更新时间:2023-10-16

我创建了两个数组,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::库与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;
  }
}

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

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

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

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

这再次迭代一次,但您甚至没有引用y