开发者

C++, fastest STL container for recursively doing { delete[begin], insert[end], and summing entire array contents}

I have some code and an array where each iteration I delete the first element, add an element at the end, and then sum the contents of the array. Naturally, the array stays the same size. I have tried using both vector and list, but both seem pretty slow.

int length = 400;

vector <int> v_int(length, z);
list <int>   l_int(length, z);

for(int q=0; q < x; q++)
{
    int sum =0;

    if(y)                       //if using vector
    {      
        v_int.erase(v_int.begin());    //takes `length` amount of time to shift memory
        v_int.push_back(z);   
        for(int w=0; w < v_int.size(); w++)
            sum += v_int[w];
    }      
    else                        //if using list
    {
        l_int.pop_front();             //constant time
        l_int.push_back(z);
        list<int>::iterator it;
        for ( it=l_int.begin() ; it != l_int.end(); it++ ) 开发者_StackOverflow//seems to take much  
            sum += *it;                                    //longer than vector does
    }
}

The problem is that erasing the first element of the vector requires that each other element be shifted down, multiplying, by the size of the vector, the amount of time taken each iteration. Using a linked list avoids this (constant time removal of elements), and should not sacrifice any time summing the array (linear time traversal of the array), except that in my program it seems to be taking way longer to sum the contents than the vector does (at least 1 order of magnitude longer).

Is there a better container to use here? or a different way to approach the problem?


Why not keep a running sum with sum -= l_int.front(); sum += z?

Also the data structure you're looking for with that delete/insert performance is a queue


Efficient additions and deletions of end elements in a container is what the deque was made for.

If you are just inserting at one end and deleting at the other then you can use a queue

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜