"JH Programmer" <ho********@gmail.comwrote:
Thank you so much!
###########################
Here are for others to search for this thread
=================================
If you want to delete a specific element in the vector "array"
you use this method
for (int i = 0; i < data.size(); i++){
if ( data[i] == data buffer ){
pos = i;
}
}
data.erase(data.begin() + pos );
Are you sure the above is what you want? It will erase the *last*
element that has the value data_buffer. So for example, given the array
{ 0, 1, 2, 2, 1, 0 } if you want to erase '1' then the above code will
produce { 0, 1, 2, 2, 0 } instead of { 0, 2, 2, 1, 0 }
You are using the loop to find something, so why not put it in a
function called "find". That will make your code more expressive:
template < typename T >
unsigned find( const vector<T>& vec, T buffer )
{
unsigned result = vec.size();
for ( unsigned i = 0; i < vec.size(); ++i )
if ( vec[i] == buffer )
result = i;
return result;
}
The above will return the last element that has the value 'buffer' or
vec.size() if no element has the value.
Of course, going through the whole container is needless, once you find
the element you want, you can stop looking...
template < typename T >
unsigned reverse_find( const vector<T>& vec, T buffer )
{
for ( unsigned i = vec.size(); i 0; --i )
if ( vec[i - 1] == buffer )
return i - 1;
return vec.size();
}
Notice that I'm going through the container backwards because I want to
find the *last* element with the particular value.
It just so happens that the standard already has a function like this,
defined in <algorithm>
vec.erase( find( vec.rbegin(), vec.rend(), buffer ).base() );
The above line will do the same thing your code segment does.
--
To send me email, put "sheltie" in the subject.