gpt4 book ai didi

c++ - 如何在自定义容器中支持范围适配器?

转载 作者:行者123 更新时间:2023-12-04 03:27:47 26 4
gpt4 key购买 nike

我创建了一个名为 goldbox 的自定义容器只包含算术类型,我也实现了beginend成员函数来迭代元素。
我的完整源代码:

#include <algorithm>
#include <vector>
#include <initializer_list>
#include <iostream>
#include <type_traits>
#include <ranges>

template <typename T>
concept Arithmetic = std::is_arithmetic_v<T>;

template <Arithmetic T = int>
class goldbox {
private:
template <Arithmetic Base_t>
struct Node {
Base_t data;
Node<Base_t>* prev;
Node<Base_t>* next;
};
Node<T>* head;
Node<T>* current_node;

Node<T>*& __at_node(size_t index) {
auto temp = head;
size_t count {0};

while (count < index) {
temp = temp->next;
count++;
}
current_node = temp;

return current_node;
}

Node<T>*& __get_tail() {
return __at_node(length() - 1);
}

public:
using value_type = T;

goldbox() : head{nullptr}, current_node{nullptr} {}
goldbox(std::initializer_list<T>&& list_arg) : goldbox() {
decltype(auto) list_1 = std::forward<decltype(list_arg)>(list_arg);
T temp[list_1.size()];
std::copy(list_1.begin(), list_1.end(), temp);
std::reverse(temp, temp + list_1.size());
for (const auto& elem : temp)
push_front(elem);
}

class iterator {
private:
Node<T>* node;
public:
iterator(Node<T>* arg) noexcept : node{arg} {}

iterator& operator=(Node<T>* arg) {
node = arg;
return *this;
}

iterator operator++() {
if (node)
node = node->next;
return *this;
}

iterator operator++(int) {
iterator iter = *this;
++(*this);
return iter;
}

iterator operator--() {
if (node)
node = node->prev;
return *this;
}

iterator operator--(int) {
iterator iter = *this;
--(*this);
return iter;
}

bool operator==(const iterator& other) {
return (node == other.node);
}

bool operator!=(const iterator& other) {
return (node != other.node);
}

T& operator*() {
return node->data;
}
};

iterator begin() {
return iterator{head};
}

iterator end() {
return iterator{nullptr};
}

size_t length() const {
auto temp = head;
size_t count {0};
while (temp != nullptr) {
++count;
temp = temp->next;
}
return count;
}

goldbox& push_front(T arg) {
auto new_node = new Node<T>;

new_node->data = arg;
new_node->prev = nullptr;
new_node->next = head;

if (head != nullptr)
head->prev = new_node;

head = new_node;
return *this;
}

goldbox& push_back(T arg) {
auto new_node = new Node<T>;
auto last = head;

new_node->data = arg;
new_node->next = nullptr;

if (head == nullptr){
new_node->prev = nullptr;
head = new_node;
return *this;
}

while (last->next != nullptr)
last = last->next;
last->next = new_node;
new_node->prev = last;

return *this;
}

goldbox& clear() {
auto temp = head;
Node<T>* next_temp;

while (temp != nullptr) {
next_temp = temp->next;
delete temp;
temp = next_temp;
}

head = nullptr;

return *this;
}

goldbox& pop_back() {
if (head != nullptr) {
if (length() != 1) {
delete std::move(__get_tail());
__at_node(length() - 2)->next = nullptr;
} else {
this->clear();
}
}
return *this;
}

goldbox& pop_front() {
if (head != nullptr) {
auto temp = head;
head = head->next;
delete temp;
}
return *this;
}
};

int main() {
goldbox goldbox_1 {2, 3, 5, 6, 7, 9};
goldbox goldbox_2;

for (const auto& elem : goldbox_1) {
std::cout << elem << ' ';
} std::cout << '\n';

std::transform(goldbox_1.begin(), goldbox_1.end(),
std::back_inserter(goldbox_2),
[](auto x){return 2 * x - 1; }
);

for (const auto& elem : goldbox_2) {
std::cout << elem << ' ';
} std::cout << '\n';

return 0;
}
输出:
2 3 5 6 7 9
3 5 9 11 13 17
但我想使用范围来使用它,这样我就不必创建新实例。
一旦我申请了 goldbox在基于范围的 for 循环内:
for (const auto& elem: goldbox_1 | std::ranges::views::transform([](auto x){return 2 * x - 1;})) {
std::cout << elem << ' ';
} std::cout << '\n';
它会引发错误,因为我没有提供 operator| .
如果我使用非管道语法:
for (const auto& elem: std::ranges::views::transform(goldbox_1, [](auto x){return x + 1;})) {
std::cout << elem << ' ';
} std::cout << '\n';
它仍然会抛出一个错误,这两个 beginend未在范围内声明。

最佳答案

TLDR
你的类(class)不满足 std::ranges::input_range因为你的迭代器不满足 std::ranges::input_iterator .在您的迭代器类中,您需要:

  • 添加默认构造函数
  • 添加公众difference_type别名
  • 使预递增和递减运算符返回引用
  • 加差运算符
  • 制作 operator==常量
  • 添加公众value_type别名
  • 添加 T& operator*() const

  • it will still throw an error that both begin and end were not declared in the scope.


    我不知道您使用的编译器会给出这种误导性错误消息。如果你用 gcc 编译,你会得到一个正确的错误诊断:

    note: the required expression 'std::ranges::__cust::begin(__t)' isinvalid

      581 |         ranges::begin(__t);
    | ~~~~~~~~~~~~~^~~~~

    cc1plus: note: set '-fconcepts-diagnostics-depth=' to at least 2 for more detail


    设置更高的 -fconcepts-diagnostics-depth=我们可以看到根本原因:

    note: no operand of the disjunction is satisfied

      114 |         requires is_array_v<remove_reference_t<_Tp>> || __member_begin<_Tp>
    | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    115 | || __adl_begin<_Tp>
    | ^~~~~~~~~~~~~~~~~~~

    你的容器不是一个数组,你没有使用 adl begin 而是 member begin 所以我们需要看看为什么你的类不满足 __member_begin :

    note: 'std::__detail::__decay_copy(__t.begin())' does not satisfyreturn-type-requirement, because

      939 |           { __detail::__decay_copy(__t.begin()) } -> input_or_output_iterator;
    | ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~

    问题是您的迭代器类实际上不是一个合适的迭代器。让我们看看为什么:

    note: the expression 'is_constructible_v<_Tp, _Args ...> [with _Tp =goldbox::iterator; _Args = {}]' evaluated to 'false'

      139 |       = destructible<_Tp> && is_constructible_v<_Tp, _Args...>;
    | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    第一个修复是使您的迭代器默认可构造。这样做然后重新编译我们看到您的类进一步不满足迭代器的概念:

    note: the required type 'std::iter_difference_t<_Iter>' is invalid,because

      601 |         typename iter_difference_t<_Iter>;
    | ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~


    note: '++ __i' does not satisfy return-type-requirement, because

      603 |         { ++__i } -> same_as<_Iter&>;
    | ^~~~~

    您需要添加 difference_type公共(public)别名并使预递增和预递减运算符返回对迭代器的引用。
    修复这个然后重新编译我们看到你的类进一步不满足迭代器的概念:

    note: 'std::__detail::__decay_copy(__t.end())' does not satisfyreturn-type-requirement, because

      136 |           { __decay_copy(__t.end()) }
    | ~~~~~~~~~~~~^~~~~~~~~~~

    error: deduced expression type does not satisfy placeholderconstraints

      136 |           { __decay_copy(__t.end()) }
    | ~~^~~~~~~~~~~~~~~~~~~~~~~~~
    137 | -> sentinel_for<decltype(_Begin{}(std::forward<_Tp>(__t)))>;
    | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    note: the required expression '(__t == __u)' is invalid, because

      282 |           { __t == __u } -> __boolean_testable;
    | ~~~~^~~~~~

    这意味着 begin() 返回的迭代器与 end 返回的迭代器不具有可比性.向下查看诊断深度,您可以看到您的 operator==不考虑,因为它不是 const。
    修复此问题然后重新编译,我们看到您的类进一步不满足 input_iterator 的概念:

    note: the required type 'std::iter_value_t<_In>' is invalid, because

      514 |         typename iter_value_t<_In>;
    | ~~~~~~~~~^~~~~~~~~~~~~~~~~~

    通过添加公共(public) value_type 来解决此问题别名。
    下一个:

    note: nested requirement 'same_as<std::iter_reference_t,std::iter_reference_t<_Tp> >' is not satisfied, because

      517 |         requires same_as<iter_reference_t<const _In>,
    | ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    518 | iter_reference_t<_In>>;
    | ~~~~~~~~~~~~~~~~~~~~~~

    这意味着 operator*应该为 iterator 返回相同的引用类型和 const iterator .这可以通过添加 const operator* 来解决。 :
    T& operator*();
    T& operator*() const;
    现在所有编译错误都已修复,并且两个版本(管道和非管道)都可以编译。请注意我已经修复了编译错误,没有检查你的语义。

    关于c++ - 如何在自定义容器中支持范围适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67343733/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com