is there a way to declare a range based array in c++ arduino for example instad of writing
const int array[] = {2,3,4,5,6};
why isn't it possible to declare an array like this?
const int array[] = {2:6};
I assume that you are not using the Arduino STL, so you could create a simple array wrapping class template, similar to std::array
, that takes two template parameters: The type, T
, and the size, N
.
Example:
template<class T, size_t N>
struct array {
// misc typedef's:
using value_type = T;
using const_pointer = const value_type*;
using pointer = value_type*;
using const_iterator = const value_type*;
using iterator = value_type*;
size_t size() const { return N; } // the fixed size of the array
// subscripting:
const T& operator[](size_t idx) const { return data[idx]; }
T& operator[](size_t idx) { return data[idx]; }
// implicit conversions when passed to functions:
operator const_pointer () const { return data; }
operator pointer () { return data; }
// iterator support:
const_iterator cbegin() const { return data; }
const_iterator cend() const { return data + N; }
const_iterator begin() const { return cbegin(); }
const_iterator end() const { return cend(); }
iterator begin() { return data; }
iterator end() { return data + N; }
T data[N]; // the actual array
};
You could then create a small helper function to create arrays and fill them with a range of values like in your question:
template<class T, T min, T max>
array<T, max - min + 1> make_array_min_max() {
array<T, max - min + 1> rv;
for(T i = min; i <= max; ++i) rv[i - min] = i;
return rv;
}
The creation would just be slightly different, but you could then use it pretty much like you use a normal array.
void func(const int* a, size_t s) { // C-style interface
for(size_t i = 0; i < s; ++i)
std::cout << a[i] << ' ';
std::cout << '\n';
}
int main() {
const auto arr = make_array_min_max<int, 2, 6>(); // create the range you want
func(arr, arr.size()); // implicit conversion to `const int*` for `arr`
for(auto v : arr) // range-based for loop
std::cout << v << ' ';
std::cout << '\n';
for(size_t i = 0; i < arr.size(); ++i) // classing loop
std::cout << arr[i] << ' ';
std::cout << '\n';
}
Output:
2 3 4 5 6
2 3 4 5 6
2 3 4 5 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.