#include <std_lib_facilities_4.h>
usingnamespace std;
struct Item {
booloperator()(const Item& Ix, const Item& Iy) const
{
double vx = Ix.value;
double vy = Iy.value;
if (vx <= vy) returntrue; // vx <= vy
returnfalse;
}
string name;
int iid;
double value;
};
//***************************
int main()
{
vector<Item> vi;
ifstream rfile("input.txt");
if (!rfile) {
cout << " Failar on opening the file!\n\n";
system("pause");
return 1;
}
string s;
int id;
double value;
for (size_t i = 0; i < 10; ++i) {
rfile >> s >> id >> value;
vi.push_back({ s, id, value });
}
sort(vi.begin(), vi.end(), Item());
reverse(vi.begin(), vi.end());
vi.insert(vi.begin(), { "horse shoe", 99, 12.34 });
vi.insert(vi.begin(), { "Canon S400", 9988, 499.95 });
for (auto i = vi.begin(); i < vi.end(); ++i)
if (i->name == "Tom") {
vi.erase(i);
break;
}
for (auto i = vi.begin(); i < vi.end(); ++i)
if (i->name == "Ted") {
vi.erase(i);
break;
}
for (constauto& v : vi)
cout << v.name << " " << v.iid << " " << v.value << endl;
cout << "\n";
system("pause");
return 0;
}
Please note the two for loops I've used for finding the two items for erasing. It works but I feel that there might be some better way instead of those loops. I tried using the find-if function but it didn't support the '==' operator.
How would you do that drill please?
The solution can also be used for the next drill (7) too.
Thanks for the reply.
This is the content of the input.txt file:
Tom 12 87.2
Jerry 18 65.5
Frank 17 88.12
Jeison 9 83.32
Kate 5 90.5
Loius 3 92.14
Crise 7 94.67
Abbasi 2 99.25
James 1 54.36
Ted 8 75.24
for (auto it = vi.begin(); it != vi.end(); ++it)
{
if(it->name == "Tom" || it->name == "Ted")
{
it = vi.erase(it);
if (it == vi.end()) // check for last elem
break;
}
}
And I think I can use a function object instead of is_odd here: v.erase( std::remove_if(v.begin(), v.end(), is_odd), v.end() );
with an overloaded operator '=='! Rather complicated as before!
What if I use an std::list instead of the std::vector in the code?
I used it and got 5 errors on algorithm::sort()!
algorithm::sort() takes Random Access Iterators as its arguments.
Are the errors because std::vector::begin and std::vector::end return Random Access Iterators and std::list::begin and std::list::end return Bidirectional Iterators?
Are the errors because std::vector::begin and std::vector::end return Random Access Iterators and std::list::begin and std::list::end return Bidirectional Iterators?
Yes, sort requires Random Access Iterators
To sort a list you can use the sort function of the list.