【问题标题】:C++ Accessing Successive Values in a 2D Array by PointerC++ 通过指针访问二维数组中的连续值
【发布时间】:2016-06-19 01:23:21
【问题描述】:

我了解如何通过指针访问二维数组中的元素,但在访问数组行中的第二个“元素”并使用它进行比较时遇到了一些麻烦。例如,如果我有数组:

int numbers[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

我需要访问元素 2、5 和 8 来获得另一个功能。但是当我声明一个指针并将其指向数组中的下一个元素时,如下所示:

int (*p)[3] = &(numbers[1]);

或

int (*p)[3] = numbers + 1;

它指向下一个元素,它本身就是数组中的下一行,因为它是一个二维数组。我明白,但我想知道是否有什么办法可以让指针指向当前行中的下一个“元素”,而不是指向下一行?

【问题讨论】:

  • 您的查询与您的原因无关

标签: c++ arrays pointers multidimensional-array


【解决方案1】:

要通过指针访问第二列的值,您可以使用指向数组第一个元素的指针和公式*(row*numberofelementsinarow+(pointer+column) 来访问数组中所需的任何内容,仅更改该公式中所需的行和列:

const int rows=3;
const int columns=3;
int numbers[rows][columns] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int * p_numbers;
p_numbers=&numbers[0][0];
for (int i=0; i<=rows-1; i++) {std::cout << *(i*columns+(p_numbers+1)) <<"\n";};

输出是: 2 5 8

【讨论】:

    【解决方案2】:

    numbers 是整数的 2D 数组,这意味着它是 3 个 1D 子数组的 1D 数组。您应该使用p 访问子数组,然后访问该一维数组中的第二个元素。下面的片段应该解释这个想法:

    int * p = 0;
    p = numbers[0]; // Now array p = {1, 2, 3}
    std::cout << p[1] << std::endl; // '2'
    
    p = numbers[1]; // Now array p = {4, 5, 6}
    std::cout << p[1] << std::endl; // '5'
    
    p = numbers[2]; // Now array p = {7, 8, 9}
    std::cout << p[1] << std::endl; // '8'
    

    【讨论】:

      【解决方案3】:

      首先,让我们了解 C++ 中数组的根本问题。

      您的数组int numbers[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 在内存中可以这样描绘,假设sizeof(int) 是4(这在您的系统上可能是也可能不是,但C++ 没有规定int 和4 的内存大小比 8 更容易绘制):

      正如我经常喜欢解释的那样,C++ 中的多维数组只是一维数组的特例,只是它的元素类型本身就是数组类型。

      在您的情况下,numbers 是一个大小为 3 且元素类型为 int[3] 的数组。整个事物在内存中是连续的,这意味着所有元素都彼此相邻放置,中间没有任何孔。 “行”和“列”的概念实际上只是一种错觉,这是由 [] 表示法如何通过在底层执行指针运算来访问单个数组元素提供的。

      获取指向“行”的指针很容易,因为“行”的元素都彼此相邻。例如,指向第二个“行”的指针只是指向“4”元素的指针,因为构成int[3]“行”的“4”、“5”和“6”元素紧挨着彼此:

      现在你想要的是一个指向“列”的指针。如图所示,在如此低的语言水平上,这是完全不可能的。例如,第二个“列”由“2”、“5”和“8”元素组成。但是,显然,没有一个地方可以让指针指向这三个元素在内存中彼此相邻放置的位置。

      “列”的概念因此只能在如此低的语言级别上非常间接地实现,通过操作而不是通过数据类型,首先遍历“行”。示例:

      // print 2nd column:
      int const column_index = 1;
      for (int row_index = 0; row_index < 3; ++row_index)
      {
          std::cout << numbers[row_index][column_index];
      }
      

      尽管如此,这是 C++,一种能够很好地抽象出这种低级机制的语言。您的问题的一种解决方案是创建一个自定义数据类型,它在内部执行间接并保持“行和列”错觉。你甚至不需要一个二维数组。一维就足够了。

      这是一个相当简单的示例(没有错误处理、硬编码值和没有const 操作):

      #include <iostream>
      
      class Column
      {
      public:
          int& element(int row_index)
          {
              return array[row_index * width + column_index];
          }
      
      private:
          friend class Matrix;
      
          Column(int width, int(&array)[9], int column_index) :
              width(width),
              array(array),
              column_index(column_index)
          {
          }
      
          int width;  
          int(&array)[9];
          int column_index;
      };
      
      class Matrix
      {
      public:
          Matrix() : width(3), array {1, 2, 3, 4, 5, 6, 7, 8, 9 }
          {}
      
          Column column(int column_index)
          {
              return Column(width, array, column_index);
          }
      
      private:
          int width;
          int array[9];
      
      };
      
      int main()
      {
          Matrix m;
      
          for (int column_index = 0; column_index < 3; ++column_index)
          {
              for (int row_index = 0; row_index < 3; ++row_index)
              {
                  std::cout << m.column(column_index).element(row_index) << " ";
              }
              std::cout << "\n";
          }
      }
      

      Column 在本例中称为代理类。 friend 声明和私有构造函数确保只有 Matrix 可以创建类的新对象。

      结合 C++ 运算符重载,你甚至可以实现原始的[][] 表示法。您实际上只是为 column 和 element 成员函数提供不同的名称:

      #include <iostream>
      
      class Column
      {
      public:
          int& operator[](int row_index)
          {
              return array[row_index * width + column_index];
          }
      
      private:
          friend class Matrix;
      
          Column(int width, int(&array)[9], int column_index) :
              width(width),
              array(array),
              column_index(column_index)
          {
          }
      
          int width;  
          int(&array)[9];
          int column_index;
      };
      
      class Matrix
      {
      public:
          Matrix() : width(3), array {1, 2, 3, 4, 5, 6, 7, 8, 9 }
          {}
      
          Column operator[](int column_index)
          {
              return Column(width, array, column_index);
          }
      
      private:
          int width;
          int array[9];
      
      };
      
      int main()
      {
          Matrix m;
      
          for (int column_index = 0; column_index < 3; ++column_index)
          {
              for (int row_index = 0; row_index < 3; ++row_index)
              {
                  std::cout << m[column_index][row_index] << " ";
              }
              std::cout << "\n";
          }
      }
      

      你最初的目标现在实现了,因为你可以完美地创建一个对象来代表一整列:

      Matrix m;
      
      Column second_column = m[1];
      
      for (int row_index = 0; row_index < 3; ++row_index)
      {
          std::cout << second_column[row_index] << " ";
      }
      

      但我们还没有到达那里。 Column 目前是一个有点危险的类,因为它不能安全地从函数中返回。对矩阵数组的内部引用很容易变成悬空的:

      Column get_column() // dangerous, see below!
      {
          Matrix m;
      
          Column second_column = m[1];
      
          // m is destroyed, but reference to its array
          // member is kept in the returned Column, which
          // results in undefined behaviour:
          return second_column;
      }
      

      这类似于迭代器对象通常不打算保留更长的时间。

      您可以禁用 Column 的复制并为其提供私有移动构造函数:

      private:
          Column(Column const&) = delete;
          Column& operator=(Column const&) = delete;
          Column(Column&& src) = default;
      

      这强烈阻止上述不良行为,因为实际上必须使 get_column 返回 Column&amp;&amp; 和 std::move 返回值才能使其编译。

      就我们上面的输出循环而言,它看起来像这样:

      Matrix m;
      
      auto&& second_column = m[1];
      
      for (int row_index = 0; row_index < 3; ++row_index)
      {
          std::cout << second_column[row_index] << " ";
      }
      

      这一切是否值得麻烦,我不知道。也许像// treat Column like an iterator, making sure that it never outlives the Matrix it refers to 这样的大评论在实践中同样有效。

      【讨论】:

        【解决方案4】:

        据我了解,您在访问多维数组的所有成员时遇到问题。这是一个如何访问所有这些的示例,您可以根据自己的使用情况进行调整。

        #include <iostream>
        
        int main() {
            int numbers[3][3] = {1, 30, 3,
                                 4, 40, 6,
                                 7, 50, 9};
        
            for(int x=0;x<3;x++) {
        
                int* row = numbers[x]; // Decay array to int pointer, pointing to numbers[x][0]
        
                for(int y=0;y<3;y++) {
        
                    std::cout<<row[y]<<" ";
        
                }
                std::cout<<"\n";
            }
        }
        

        输出:

        1 30 3
        4 40 6
        7 50 9
        

        【讨论】:

          【解决方案5】:

          试试这个代码:

          int numbers[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
          cout << *(*(numbers+2) + 1); 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-07-26
            • 1970-01-01
            • 2010-09-25
            • 2013-02-13
            • 1970-01-01
            • 1970-01-01
            • 2016-02-21
            • 1970-01-01
            相关资源
            最近更新 更多