Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector::erase(item) needs assignment operator to be defined for item?

I have a class C which does not define operator=. I have am trying to use a vector like so: std::vector<std::pair<C,D>> vec;. Now, my problem is that I am not able to erase the pair after I am done with it. The compiler complains of missing operator= for C. Can I not have a vector of a class which does not have this operator? How do I get around this? I cannot add assignment to C. This is the error I get:

error C2582: 'operator =' function is unavailable in 'C'    C:\...\include\utility  196 1   my-lib

This is my code:

void Remove(const C& c) 
{
    auto i = cs_.begin();
    while( i != cs_.end()) {
        if (i->first == c) {
            cs_.erase(i);  // this is the problem
            break;
        }
        i++;
    }
 }

where cs_ is:

std::vector<std::pair<C,D>> cs_;
like image 253
341008 Avatar asked Jan 23 '14 14:01

341008


People also ask

How do you find the element of a vector and delete it?

In order to remove all the elements from the vector, using pop_back(), the pop_back() function has to be repeated the number of times there are elements. The erase() function can remove an element from the beginning, within, or end of the vector.

What does erase function do in C++ vector?

C++ Vector Library - erase() Function The C++ function std::vector::erase() removes single element from the the vector. This member function modifies size of vector.

Does vector erase delete object?

Yes. vector::erase destroys the removed object, which involves calling its destructor.

What happens when you use an assignment operator with objects?

The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity.


1 Answers

The reason is that erase will reallocate your objects if you erase a different position than std::vector::end(). A reallocation implicates copying.

Notice that a vector of an uncopyable type is only partially useable. Before we had emplace() (pre-C++11) it was even impossible. If your class is however copyable, why dont you define an assignment operator then?

A workaround could be a vector of smartpointers (or normal pointers) like std::vector<std::unique_ptr<C>>

like image 190
Sebastian Hoffmann Avatar answered Nov 01 '22 14:11

Sebastian Hoffmann