简体   繁体   中英

Append and clear for a list c++

I'm trying to realize two methds append() and clear() .

In appened() , I need to newPoint to the end of a list. If the list is empty, then adds newPoint as the first(and only) point in the list.

In clear() ,I need to remove all the points in a list.

Can you give me some advice to realize appened and clear . Here is a code:

//
#pragma once
const int maxListSize = 10;

class Point
{
private:
    float x;
    float y;
public:
    Point(float x0 = 0, float y0 = 0)
    {
        x = x0;
        y = y0;
    }
};


class PointList
{
private:
    //Data members
    int size;
    int cursor;
    Point points[maxListSize];
public:
    PointList();
    //List Manipalution operations 
    void append(Point newPoint);
    void clear();

    ~PointList();
};

*I don't need you to write everything for me, just give me some advice. I would like to realize it by myself. Thank you for helping.

Since you store your list elements by value ( Point points[maxListSize] ), it is quite easy to do:

PointList() :size(0) {}
void append(Point newPoint) { points[size++] = newPoint; }
void clear() { size = 0; }

This assumes that your Point object doesn't manage any resource, which is true for this particular example. Otherwise, inserted Point objects should be destroyed in clear.

To get the semantics that you're probably expecting for appending new items, and clearing out existing items, I suggest you look at the placement new operator, and manually calling the destructor of an item in the list.

Currently your class will construct all of the items in the list when you create the list. This can be quite time consuming for complex structures. Then, instead of the constructor for your elements being called, you'll instead be calling the copy-assignment operator, as the items are already constructed.

If you store your array as

char * points[sizeof(Point)*maxListSize];

Any only initialize the items when they're actually added, you avoid the construction cost when you create the list.

Your append function takes it's argument by value. Instead, I recommend you have two append functions. One that takes const&, and the other that takes an rvalue-reference. Then, inside the append function, call the placement new operator on the address of the next location in your array.

To clear the array, simple call the destructor for each element in the array one at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM