Remove continuous duplicate I've made a little function to eliminate continuous duplicate from a std::vector. I have to use C++03.

For example, if a vector of ints is composed of: 1,1,2,3,,3,1,1,2 my function should return 1,2,3,1,2. I've tried to use templates (I've just began to use c++) and made it as fast as possible!

template&lt;class T&gt;
vector&lt;T&gt; remove_duplicate(vector&lt;T&gt;&amp; vec) {
    int length = vec.size();
    vector&lt;T&gt; result(length);
    result[0] = vec[0];
    int last = 0;
    for(int i=0; i&lt;length; i++)
        if(vec[i] != result[last]){
            last++;
            result[last] = vec[i];
        }
    result.resize(last+1);
    return result;
}


Here's a simple test case:

static
void test_remove_duplicate() {
    vector&lt;int&gt; v;
    v.push_back(1); //123131
    v.push_back(1);
    v.push_back(2);
    v.push_back(2);
    v.push_back(3);
    v.push_back(1);
    v.push_back(3);
    v.push_back(3);
    v.push_back(1);
    v.push_back(1);

    vector&lt;int&gt; v1;
    v1 = remove_duplicate(v);
    for(int i=0; i&lt;v1.size(); i++) {
        cout &lt;&lt; v1[i];
    } cout &lt;&lt; endl;
}


What do you think about it?
Let's go through mechanical errors:


use size_t instead of int

int length = vec.size();

what if there is no zero element?

result[0] = vec[0];

the same as first:

int last = 0;

the same as 1, 3:

for(int i=0; i&lt;length; i++)



Optimization errors:


Is there any reason why do you need to return a COPY of vector? If you need return copy, so why do you pass it by reference?
Extra resize of vector is extremely heavy and slow operation.

result.resize(last+1); 

Prefer pre-increment to post-increment
use reserve and push_back, instead of resize and []. In you case result.size() &lt;= v.size(). So, make following:

std::vector&lt;T&gt; result;
result.reserve(v.size);
result.push_back( vec[0] );


In the loop:

result.push_back( vec[i] );



So, including all comments above:

template&lt;class T&gt;
std::vector&lt;T&gt; remove_duplicate(const std::vector&lt;T&gt;&amp; vec)
{
    std::vector&lt;T&gt; result;

    if(!vec.empty())
    {
        result.reserve(vec.size());
        result.push_back(vec.front());

        for(size_t i = 0; i&lt; vec.size(); ++i)
            if(vec[i] != result.back())
                result.push_back( vec[i] );
    }

    return result;
}