|If you didn't use 'auto' as the data type for 'iter', what would be the appropriate label?|
Same as you had it in your original code.
for a normal non-const iterator. Or
for a const iterator.
Since you have a vector of strings:
std::vector<std::string>::const_iterator iter = favG.begin();
Of course that is really long to type out, so
is much easier. Also, it doesn't scale well, because if you decide to change your vector to a list or something in the future, then you have to change the 'iter' type as well, whereas if you use auto the iterator will change to the appropriate type automatically.
|Also I added an int i and set it equal to 1 if something gets erased.|
Avoid generic one-letter names unless what you're representing is clearly obvious. In the case of an iterator or loop counter, a variable name like 'i' is fine. But for anything else you want to be descriptive.
Something like 'entryErased' would be much more clear and would go a long way in telling other people (or yourself in 2 months) what your code is doing.
To take that clarity step a bit further, if the 'entryErased' variable only has 2 states, you might want to make it a
, and use
rather than 0 and 1.
|Is this a standard way of checking to see if an item is there are not?|
For small scale projects it's a fine approach. However it does have one problem: erase is somewhat of an expensive operation in a vector, because erasing an element means you have to shift over elements after it.
This is no big deal if the vector is small, but if you have a vector of 10,000+ elements and you are erasing 50 of them... it can get expensive.
One way around this is to use the
function in the
header. The name is somewhat misleading because it doesn't modify the size of the vector. The reference page might explain it better:
But basically, remove will return an iterator that will be the new end of the vector. Then we can do a single erase() to erase all of them at once:
auto newEnd = std::remove( favG.begin(), favG.end(), "The thing to erase" );
if( newEnd == favG.end() )
// elements not found in vector
// elements found in vector
entryErased = true;
favG.erase( newEnd, favG.end() ); // erase all elements from newEnd and onward