Reputation: 73
I want to sort chopsticks by weight and I want the matching pair of chopstick at the end of program. Should I use sort algorithm? I want to sort it by weight means (e.g 110, 90, 110, 90) so in this case I got 2 pair. One having weight 90 and other having weight 110, but how can I track that? I know I have to use counter but how I don not know.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool myChopsticks (int i, int j)
{
return (i<j);
}
int main()
{
int myintergers []= {90, 110, 90, 110};
vecotr<int> myvector(myintergers, myintergers+4);
vector<int>::iterator it;
sort (myvector.begin(), myvector.end()+2);
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it; cout << endl;
return 0;
}
Upvotes: 0
Views: 332
Reputation: 54148
If you know there is only one matched pair, then use a std::map<weight, chopstick>
and insert at given point after doing a find(newWeight)
call. If find()
returns an exact match at any point then you are done.
If there is more than one possible matching pair then use std::multimap<weight, chopstick>
and then iterate the resulting container to count()
the number of matches for each distinct value.
If you don't need the actual chopsticks at the end, but just a count of matching pairs, then you can use std::set<weight>
or std::multiset<weight>
instead.
Upvotes: 0
Reputation: 7476
It seems enough to store a list of chopsticks (possibly in a vector<>) then either iterate through them to find the match(es) and display it.
Alternately a std:mapping implements a binary tree for you that should make the search for matches very efficient.
Upvotes: 0
Reputation: 22624
Yes, I think so.
By sorting the chopsticks, you will have them in order. Then, it will be much easier (with just a single iteration through the ordered set) to find the pairs with equal weight.
Upvotes: 1