我有一個這樣的陣列[1, 0, 1, 1, 0, 0, ...]。
我怎樣才能得到這個運算式的結果:1 XOR 0 XOR 1 XOR 1 XOR...沒有回圈?
uj5u.com熱心網友回復:
在 C 14 中:
std::accumulate(arr.begin(),
arr.end(),
0,
std::bit_xor<void>())
uj5u.com熱心網友回復:
您可以創建一個函式模板,它接受一個陣列并使用make_index_sequence-轉發到一個輔助函式,然后使用折疊運算式來“解包”該陣列。
這不需要任何回圈,因為運算式將在編譯時創建。
#include <utility>
namespace detail {
template<class T, std::size_t... I>
auto Xor_helper(const T& arr, std::index_sequence<I...>) {
// make a fold expression of the whole array:
return (... ^ arr[I]); // arr[0] ^ arr[1] ^ ...
}
} // namespace detail
template<class T, size_t N>
auto Xor(const T(&arr)[N]) {
return detail::Xor_helper(arr, std::make_index_sequence<N>{});
}
你可以像這樣用你的陣列呼叫它:
int main() {
int arr[] = {0xf, 0x1, 0x3};
std::cout << std::hex << Xor(arr) << '\n';
}
輸出:
d
您可以在@cppinsights 中看到這些模板會變成什么樣。只要按下?按鈕,你就會看到上面Xor(arr)變成return (arr[0UL] ^ arr[1UL]) ^ arr[2UL];
上面的折疊運算式至少需要 C 17。從 C 98 開始作業的解決方案可以改用遞回。
例子:
namespace detail {
template<std::size_t> struct index_tag{}; // one type per index used
template<class T, size_t N, size_t I> // main function template
T Xor_helper(const T(&arr)[N], index_tag<I>) {
// recurse using `index_tag<I - 1>`:
return Xor_helper(arr, index_tag<I - 1>()) ^ arr[I];
}
// Recursion stops when `index_tag<0>` is used:
template<class T, size_t N> // terminating case
T Xor_helper(const T(&arr)[N], index_tag<0>) {
return arr[0]; // no recursion, just return the value
}
} // namespace detail
template<class T, size_t N>
T Xor(const T(&arr)[N]) {
// Call the helper using the index_tag for the last index in the array:
return detail::Xor_helper(arr, detail::index_tag<N - 1>());
}
您還可以看到這些模板將如何實體化@cppinsights。
uj5u.com熱心網友回復:
有效:
std::accumulate(arr.begin(), arr.end(), arr[0], std::bit_xor());
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/355677.html
