我有一个链表代码:
#include <iostream>
class Node
{
private:
/* data */
public:
int value;
Node* next;
Node(int value){
this->value = value;
this->next = nullptr;
}
};
class LinkedList
{
private:
/* data */
public:
Node *start;
LinkedList(){
this->start = nullptr;
}
void insert(int value){
Node *node = new Node(value);
if (this->start == nullptr)
{
this->start = node;
}else
{
Node* temp = this->start;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = node;
}
}
void print(){
Node* temp = this->start;
while (temp != nullptr)
{
std::cout<<temp->value<<std::endl;
temp = temp->next;
}
}
void __iter__(){
Node* node = this->start;
while (node)
{
yield node;
node = node->next;
}
}
};
int main(int argc, char const *argv[])
{
LinkedList listed;
listed.insert(4);
listed.insert(7);
listed.insert(9);
listed.insert(6);
listed.print();
return 0;
}
如您所见,我的 LinkedList
类中有 __iter__
方法,但我发现 yield
未定义在 C++ 中使用,所以我的控制台只显示:
info.cpp: In member function 'void LinkedList::__iter__()':
info.cpp:59:13: error: 'yield' was not declared in this scope
59 | yield node;
| ^~~~~
我正在引用下一段Python代码:
def __iter__(self):
node = self.start
while node:
yield node
node = node.next
希望您能帮我解决这个问题,谢谢。
最佳答案
看看这个来源:https://en.cppreference.com/w/cpp/iterator/iterator
它是这么说的
std::iterator
is the base class provided to simplify definitions of the required types for iterators.
此外:
此来源https://cplusplus.com/reference/iterator/iterator/
为您提供以下示例:
// std::iterator example
#include <iostream> // std::cout
#include <iterator> // std::iterator, std::input_iterator_tag
class MyIterator : public std::iterator<std::input_iterator_tag, int>
{
int* p;
public:
MyIterator(int* x) :p(x) {}
MyIterator(const MyIterator& mit) : p(mit.p) {}
MyIterator& operator++() {++p;return *this;}
MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
bool operator==(const MyIterator& rhs) const {return p==rhs.p;}
bool operator!=(const MyIterator& rhs) const {return p!=rhs.p;}
int& operator*() {return *p;}
};
int main () {
int numbers[]={10,20,30,40,50};
MyIterator from(numbers);
MyIterator until(numbers+5);
for (MyIterator it=from; it!=until; it++)
std::cout << *it << ' ';
std::cout << '\n';
return 0;
}
它包括通过 #include <iterator>
的迭代器,将其操作定义为 public
然后在main
里面函数有效地使用了它。您将需要应用类似的东西,但您将需要在 operator++
的指针之间步进。方法。
关于python - 如何在C++中创建一个可迭代的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73847581/