C++正在将元素复制到新列表中
C++ Copying elements into new list
我在将列表的一些元素复制到新元素时遇到问题。必须在一个条件下完成:可以复制的元素必须来自输入的范围。问题是,每个元素都被复制到newlist中。有什么建议吗?我想指出的是,我的英语并不完美,但我希望你能理解。谢谢:)
struct Node
{
Node* next;
int data;
};
struct List
{
Node* head;
Lista();
void push(int);
void addafter(int, int);
void delchosen(int);
void pop();
void print();
int count();
Node* find(int);
void pushback(int);
void popback();
void minmax(int&, int&);
List* range(int, int);
};
List::List()
{
head = NULL;
}
void List::push(int value)
{
Node *p = new Node;
p->data = value;
p->next = head;
head = p;
}
List* List::range(int x, int y)
{
Node* e = head;
List* newlist = new List;
while(e)
{
if(e->data > x && e->data <y)
{
newlist->push(e->data);
}
e = e->next;
}
return newlist;
}
int main()
{
List l;
srand(time(NULL));
const int size = 30;
int* arr = new int [size];
for(int i=0; i<size; i++)
{
arr[i]=rand()%20+1;
l.push(arr[i]);
}
l.range(3, 10);
return 0;
}
我觉得没有必要,但我只是编辑了代码。除了复制之外,每一个函数都可以正常工作。
您永远不会使用新列表。这可能会误导你。例如,您可以在调试器中打印或查看旧列表,该列表仍然包含所有值。这种情况有时会发生在所有的程序员身上,从大一新生到老胡子大师。
否则代码应该工作:
auto newList = l.range(3, 10);
newList->print();
奖金:一般代码审查
如果用确定性值而不是随机内容来填充列表,那么调试和测试代码可能会更容易:
for (int i = 0; i < size; i++) { l.push(i); }
很可能您不需要在堆上分配
newlist
。使用堆栈分配:List List::range(int x, int y) const { ... List newlist; ... newlist.push(...); ... return newlist; }
虽然这对自我教育和各种黑客攻击来说既好又有趣,但你应该避免在严肃的代码中使用自制链接列表。在C++中,我们倾向于使用标准库设施。类似于:
#include <iostream> #include <iterator> #include <list> int main() { // Construct original list from brace-initializer list std::list<int> original{ 1, 2, 3, 4, 5, 6, 7 }; // Get the beginning of the new list by advancing // beginning of the original list by 2 elements auto begin = original.cbegin(); std::advance(begin, 2); // Get the end of the new list by advancing // beginning of the original list by 5 elements auto end = original.cbegin(); std::advance(end, 5); // Construct sublist from iterator range std::list<int> sublist(begin, end); // Print new list for (auto&& e : sublist) std::cout << e << ' '; // prints "3 4 5" }
相关文章:
- C++模板函数中的初始化 - 新的初始值设定项表达式列表被视为复合表达式
- 将新元素添加到列表中,并返回对该元素的引用?
- 将列表 en 列表迭代器作为指针 C++ 传递
- 通过查找一对项目的代码获取错误的输出,在给定的总和相等的给定列表中列表
- 如何获取两个列表的公共元素并将其存储在新列表中而不会重复
- 如何将 2 个链表合并或合并在一起以创建新列表
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- 与内存堆有关的C 链接列表(STD ::列表)是否使用新的
- RCPP:处理包含列表的列表
- 基本STL:向量列表或列表向量,在这种特殊情况下哪个会更好
- 图形、顶点、STL 列表:为什么列表是空的
- 如何定义映射::迭代器的列表和列表::迭代器的映射
- 我如何解码一个列表的列表
- 迭代一对列表,列表在数组中
- 将递增数量的列表子列表存储在vector中
- 在c++中如何像Java那样定义列表的列表或堆栈的列表
- 我如何创建一个稀疏矩阵作为列表的列表?(c++)
- 从字符串列表的列表映射中获取字符串
- C++正在将元素复制到新列表中
- 数组列表vs列表