簡體   English   中英

通用 find_if 檢查二維數組中的元素

[英]Generic find_if to check an element in the 2D array

使用std::find_if我們可以找到一個元素是否存在於一個正常的一維 arrays 中。

受到這個問題的啟發,我想知道,我們是否可以提供一種算法 function 來檢查任何二維數組(即std::vectorstd::vectorstd::arra std::array的任何類型和任意數量的元素。

是否可以提供通用 function 來查找二維數組中元素的存在?

就像是:

template<typename Iterator>
auto isIn2DArray(
   Iterator begin, const Iterator end, ElementType ele) noexcept
{
   // returns the iterator pointing to the row, if the element is found, otherwise the end of the array!
}

在相同的std::find_if的幫助下,我們可以實現這一點。

以下是一個模板 function ,它采用二維數組( std::vector<std::vector<Type>>std::array<std::array<Type, RowSize>, ColSize> ) 並返回指向內部數組(元素所在的位置)的迭代器,否則返回二維數組的結束迭代器。

見在線直播

#include <type_traits>   // std::remove_reference_t, std::remove_const_t, std::conditional_t, std::is_fundamental_v
#include <iterator>      // std::cbegin(), std::cend()
#include <algorithm>     // std::find_if
#include <utility>       // std::declval

// traits for finding the inner element type of 2D array(of std::vector or std::array)
template<typename Iterator>
using ContainerType = std::remove_const_t<std::remove_reference_t<decltype(*std::declval<Iterator>())>>;

template<typename Iterator>
using ElementType = std::remove_const_t<std::remove_reference_t<typename ContainerType<Iterator>::value_type>>;

template<typename Iterator>  // optional: ElementType<Iterator> should also be enough!
using ElementArgumentType = std::conditional_t<std::is_fundamental_v<ElementType<Iterator>>
   , ElementType<Iterator>, ElementType<Iterator> const&>;

template<typename Iterator>
auto isIn2DArray(
   Iterator begin, const Iterator end, ElementArgumentType<Iterator> val) noexcept
{
   // used the standard algorithm std::find_if here!
   return std::find_if(begin, end, [val](const auto& row) noexcept {
      return std::find_if(std::cbegin(row), std::cend(row), [val](const auto& element) noexcept {
         return element == val;
         }
      ) != std::cend(row);
      }
   );
}

或者將一元謂詞傳遞給 function,它將用於在 arrays 數組中查找適當的數組。 這樣噪音會小一點!

見在線直播

#include <iterator>      // std::cbegin(), std::cend()
#include <algorithm>     // std::find_if


template<typename Iterator, typename UnaryPredicate>
auto find_if_in_2DArray(
   Iterator begin, const Iterator end, UnaryPredicate unarayPred) noexcept
{
   // used the standard algorithm std::find_if here!
   return std::find_if(begin, end, [unarayPred](const auto& row) noexcept {
      return std::find_if(std::cbegin(row), std::cend(row), unarayPred) != std::cend(row);
      }
   );
}

暫無
暫無

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

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