Searching arrays that are a class.

How would i go about doing a sequential search on an array that is a class? This
code is not working. Thanks for your help!!!


int removeFromCart(CartItem cart[50])
{
string item;
cout << "Name of cart item to be removed: ";
cin >> item;
bool isFound = false;
int i = 0;
while (!isFound && i < 50)
{
if (cart[i] == item)
isFound = true;
++i;
}
// It is typical to return the index to the value or a -1 if
// not found
if (isFound)
{
cout << "Is found";
}
else
cout << "Is not found";

return 0;
}
A C-style array, such as the one you're using, can't be adjusted for size once it's been declared so you can't really remove the item(s) from the container but what you could do is to shift it/them to the end and print out only the items that are not 'removed'.

On the other hand if you were using std::vector<CartItem> for e.g. then a true removal from the container would have been possible through the erase-remove_if idiom: https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom

In either case, remove_if is the function you're looking for:
http://en.cppreference.com/w/cpp/algorithm/remove
http://www.cplusplus.com/reference/algorithm/remove_if/

And use getline() instead of cin for strings in case the string item has white-space
Topic archived. No new replies allowed.