I'm having problem with deducing a type of a single element of an c++ array.
I would like to do achieve something like:
template <class T>
struct array_element { };
template <class T>
struct array_element<T[]> {
using type = T;
};
int main() {
int a[5] = {1, 2, 3, 4, 5};
array_element<decltype(a)>::type element = a[0];
}
But the code obviously does not compile (the int[5] does not match T[])...
If you need the index of the found element in the array, use findIndex() . If you need to find the index of a value, use indexOf() .
The way to find the unique element is by using the XOR bitwise operator which returns 1 only if one of the element is 1 and false otherwise. In the loop, each of the integers in the array are XORed with uniqueId starting at 0. Then, 0 is XOR'ed with 34.
An array with a size of 1 can hold exactly one element at index 0.
Element − Each item stored in an array is called an element. Index − Each location of an element in an array has a numerical index, which is used to identify the element.
You need an extra argument for the specialization:
template <class T, size_t N>
struct array_element<T[N]> {
using type = T;
};
Alternatively:
std::remove_reference<decltype(a[0])>::type element = a[0];
Or:
auto element = a[0];
Use std::remove_extent
template class (C++11) or std::remove_extent_t
alias template (C++14) to get a type of an array element (both are declared in type_traits
header file):
std::remove_extent<decltype(a)>::type element0 = a[0];
std::remove_extent_t<decltype(a)> element1 = a[1];
Live demo
You can also use std::remove_all_extents
(C++11) or std::remove_all_extents_t
(C++14) to get a type of an element of a multidimensional array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With