簡體   English   中英

如何處理C ++預處理程序宏中的數組元素?

[英]How can I process array elements in a c++ preprocessor macro?

對於一項家庭作業,我們被要求編寫一個預處理器宏,該宏對數組的元素求和。

我的問題是,如何處理宏中的數組元素,使其可以擴展為總和(或對元素進行任何其他數學運算)?

在我們的書中,沒有任何東西提到處理數組元素甚至訪問它們,而且我無法在線找到許多有用的資源,因為宏不是處理此類問題的典型方法。 我知道有更好的方法可以做到這一點,但我知道這樣做的目的是使我們更好地了解預處理器宏。

當我打算以函數樣式編寫宏時,我不知道如何將總和“返回”到程序中。 我能想到的將宏擴展為總和的唯一方法是是否以遞歸方式進行,而且我甚至不確定是否可以使用宏進行遞歸。 我已經編寫了一個宏,該宏可以成功擴展到數組的大小,但是我不確定從那里開始的方向。

這是使用c ++ 14的答案:

#include <array>
#include <iostream>
#include <numeric>
#include <type_traits>
#include <vector>

#define SUM(ARY) \
  std::accumulate( \
      std::begin(ARY), \
      std::end(ARY), \
      std::remove_reference_t<decltype(ARY[0])>{})
int
main()
{
  auto ary1 = std::array< int, 5 >{1,2,3,4,5};
  std::cout << SUM(ary1) << "\n";

  int ary2[] = {1,2,3,4,5};
  std::cout << SUM(ary2) << "\n";

  auto ary3 = std::vector< int >{1, 2, 3, 4, 5};
  std::cout << SUM(ary3) << "\n";

  double ary4[] = {1.1,2.2,3.3,4.4,5.5};
  std::cout << SUM(ary4) << "\n";
}

請注意,您不會從宏“返回”。 宏是文本替換。 在上面顯示SUM(ary) ,將其替換為SUM(ARY)宏定義的擴展文本。

您可以將此擴展到其他操作:

#include <array>
#include <iostream>
#include <numeric>

#define OP_ON_ARY(ARY, OP) \
  std::accumulate( \
      std::next(std::begin(ARY)), \
      std::end(ARY), \
      *std::begin(ARY), \
      [](auto a, auto b) { return a OP b; } \
      )

int
main()
{
  auto ary = std::array< int, 5 >{1,2,3,4,5};
  std::cout << OP_ON_ARY(ary, +) << "\n";
  std::cout << OP_ON_ARY(ary, -) << "\n";
  std::cout << OP_ON_ARY(ary, *) << "\n";
}

但是使用函數而不是宏更符合現代c ++的精神。

#include <array>
#include <iostream>
#include <numeric>
#include <vector>

template< typename Ary >
auto sum(Ary const & ary)
{
  return std::accumulate(
      std::begin(ary),
      std::end(ary),
      decltype(ary[0]){});
}

int
main()
{
  auto ary1 = std::array< int, 5 >{1,2,3,4,5};
  std::cout << sum(ary1) << "\n";

  int ary2[] = {1,2,3,4,5};
  std::cout << sum(ary2) << "\n";

  auto ary3 = std::vector< int >{1, 2, 3, 4, 5};
  std::cout << sum(ary3) << "\n";

  double ary4[] = {1.1,2.2,3.3,4.4,5.5};
  std::cout << sum(ary4) << "\n";
}

預處理程序實際上執行許多查找和替換操作。 它沒有任何真正高級的功能,當然也不知道數組是什么。 我以為該分配要求您執行的操作是編寫一些內聯代碼以對數組或某些內容求和,然后為其創建一個宏。

#define fold(array, ln, acc, op) \
  for(size_t i = 0; i < ln; ++i) \
    acc = acc op array[i];

int main(){
  int ar[10];
  int sum = 0;
  fold(ar, 10, sum, *); 
}

此代碼使用*操作折疊數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM