I am writing a program that has a customer class with a simple vector of strings in it. I want to delete a video if it has been returned and I'm using the erase function as it is given in the textbook. Visual studio is showing an error under my dot operator. The dot operator cannot be overloaded so I'm confused as to why it is giving me this error. I have included the vector library and my variables are defined in the class header file. Hope this is enough info. Thanks for any help you can give me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void CustomerType::returnVideo(string v)
{
if (videosRented.empty())
cout << "Customer has no videos rented.\n";
elsefor (int i=0; i < numRentals; i++)
{
if (videosRented[i] == v)
{
videosRented.erase(i);
numRentals--;
}
}
}
The only way to delete an element of a vector is to either pass as parameter an iterator to that element or specify a range by an iterator pointing at where to start deleting from and iterator to the last element not included in the erasing process
Class std::vector has only two overloaded member functions erase. The both accept iteratora as arguments. There is no such member function erase that accepts an argument of type int.
Also it is a bad idea to keep separate variable numRentals for number of elements (as I have understood) in the vector. Vector has member function size() that gives the exact number of elements in the vector.
I would rewrite your function the following way
1 2 3 4 5 6 7 8 9 10
#include <algorithm>
#include <vector>
void CustomerType::returnVideo( const string &v )
{
if ( videosRented.empty() )
cout << "Customer has no videos rented.\n";
else
videosRented.erase( remove( videosRented.begin(), videosRented.end(), v ), videosRented.end() );
}
If the vector may contain only one element with the given string then the code will look the following way
1 2 3 4 5 6 7 8 9 10
#include <algorithm>
#include <vector>
void CustomerType::returnVideo( const string &v )
{
if ( videosRented.empty() )
cout << "Customer has no videos rented.\n";
else
videosRented.erase( find( videosRented.begin(), videosRented.end(), v ) );
}
When you pass a string by value then either copy contsructor or move constructor is called.
When you pass a string by reference there is no any overload by calling either constructor.