我正在寻找一种可读,优雅的方式在C++中执行以下操作,这里显示在Python中:
for datum in data[1:]:
do work.
Run Code Online (Sandbox Code Playgroud)
有问题的数据上的迭代器可能不支持随机访问迭代器,所以我不能只使用:
for (mIter = data.begin() + 1; mIter != data.end(); mIter++)
Run Code Online (Sandbox Code Playgroud)
我提出的最好的是以下内容:
iterable::iterator mIter = data.begin();
for (mIter++; mIter != allMjds.end(); mjdIter++) {
do work.
}
Run Code Online (Sandbox Code Playgroud)
它不是太冗长,但它几乎不是说明性的 - 乍一看它实际上看起来像是一个错误!
另一种解决方案是拥有一个"第n个元素"辅助函数,我猜.任何冷静的想法?
所以,假设您有一个递归的基类(例如链表)和派生类.派生类应该重用基类中的构造函数,因为您不想编写冗余代码.你可以尝试一下这个显而易见的事情,它不会起作用:
class Base {
public:
Base(int size) {
if (size <= 0) { next = NULL; }
else { next = new Base(size - 1); }
}
void print() {
cout << " Base ";
if (next != NULL) { next->print(); }
}
protected:
Base *next;
};
class Derived: public Base {
public:
Derived(int size) : Base(size) {}
void print()
{
cout << " Derived ";
if (next != NULL)
{ next->print(); }
}
};
int main()
{
Derived d2(5); …Run Code Online (Sandbox Code Playgroud) c++ ×2
coding-style ×1
compilation ×1
inheritance ×1
iterator ×1
readability ×1
recursion ×1
templates ×1