tags:

views:

171

answers:

3

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;
}
+1  A: 

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.

Daniel Daranas
A: 

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.

Elemental
A: 

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.

Steve Townsend
How to use count() in above program?
Cool
I imagine this homework is intended to help you learn independently as well as research. I don't intend to actually write your code. If you would care to update your question with any alternate attempts, I am sure people will be glad to help you workout why it's not working. Good luck.
Steve Townsend
Here's a pointer to get you started on the multimap container: http://msdn.microsoft.com/en-us/library/1ka6hya8(v=VS.71).aspx
Steve Townsend