【问题标题】:is there a way to declare a ranged based array in c++ arduino?有没有办法在 c++ arduino 中声明一个基于范围的数组?
【发布时间】:2021-12-27 21:03:45
【问题描述】:

有没有办法在 c++ arduino 中声明一个基于范围的数组,例如 instad of writing

const int array[] = {2,3,4,5,6};

为什么不能像这样声明一个数组?

const int array[] = {2:6};

【问题讨论】:

  • 因为c++中没有这样的语法。
  • 如果范围很小,最好的办法是输入数字。 vector 有一些选项:https://en.cppreference.com/w/cpp/algorithm/iota
  • 不过是对语言的一个很好的补充。特别是如果扩展到包括包容性和排斥性范围符号。

标签: c++ arrays


【解决方案1】:

我假设您没有使用 Arduino STL,因此您可以创建一个简单的数组包装类模板,类似于 std::array,它采用两个模板参数:类型 T 和大小 @987654323 @。

例子:

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
};

然后您可以创建一个小的辅助函数来创建数组并用您的问题中的一系列值填充它们:

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;
}

创建会略有不同,但您可以像使用普通数组一样使用它。

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';
}

输出:

2 3 4 5 6 
2 3 4 5 6 
2 3 4 5 6 

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 2020-07-15
    • 2018-06-05
    • 2015-11-05
    • 1970-01-01
    • 2021-10-14
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多