array vs vector vs list

前端 未结 8 769
日久生厌
日久生厌 2020-11-28 20:34

I am maintaining a fixed-length table of 10 entries. Each item is a structure of like 4 fields. There will be insert, update and delete operations, specified by numeric posi

8条回答
  •  情话喂你
    2020-11-28 20:51

    I am maintaining a fixed-length table of 10 entries. Each item is a structure of like 4 fields. There will be insert, update and delete operations, specified by numeric position. I am wondering which is the best data structure to use to maintain this table of information:

    Based on this description it seems like list might be the better choice since its O(1) when inserting and deleting in the middle of the data structure. Unfortunately you cannot use numeric positions when using lists to do inserts and deletes like you can for arrays/vectors. This dilemma leads to a slew of questions which can be used to make an initial decision of which structure may be best to use. This structure can later be changed if testing clearly shows its the wrong choice.

    The questions you need to ask are three fold. The first is how often are you planning on doing deletes/inserts in the middle relative to random reads. The second is how important is using a numeric position compared to an iterator. Finally, is order in your structure important.

    If the answer to the first question is random reads will be more prevalent than a vector/array will probably work well. Note iterating through a data structure is not considered a random read even if the operator[] notation is used. For the second question, if you absolutely require numeric position than a vector/array will be required even though this may lead to a performance hit. Later testing may show this performance hit is negligible relative to the easier coding with numerical positions. Finally if order is unimportant you can insert and delete in a vector/array with an O(1) algorithm. A sample algorithm is shown below.

    template 
    void erase(vector & vect, int index) //note: vector cannot be const since you are changing vector
    {
      vect[index]= vect.back();//move the item in the back to the index
      vect.pop_back(); //delete the item in the back
    }
    
    template 
    void insert(vector & vect, int index, T value) //note: vector cannot be const since you are changing vector
    {
      vect.push_back(vect[index]);//insert the item at index to the back of the vector
      vect[index] = value; //replace the item at index with value
    }
    

提交回复
热议问题