C++正在将元素复制到新列表中

C++ Copying elements into new list

本文关键字:列表 新列表 元素 复制 C++      更新时间:2023-10-16

我在将列表的一些元素复制到新元素时遇到问题。必须在一个条件下完成:可以复制的元素必须来自输入的范围。问题是,每个元素都被复制到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"
    }