For a hw assignment, we are to code a reduce routine that looks like:
int reduce(long array[], int size)
//Where array is the array to reduce, and size is the size of the array.
Using STL. My initial thoughts were to create a set, put all items in the set with a comparison, but then I realized that the set I would create would never be usable since the function returns the size of the new set, but not the set itself to be used. So I'm not sure how I'd go about using the STL to r开发者_StackOverfloweduce an array. Any thoughts? Thanks.
Edited: Sorry, reduce is just to reduce the array into a sorted array without duplicates.
E.g. {4, 4, 2, 1} -> {1, 2, 4}
Sort the array using std::sort, then apply std::unique on it to remove duplicates. std::unique works only on sorted arrays. Just to simplify matters here is how you get begin
and end
of a native array:
long* begin = array;
long* end = array + size;
Once you have these two things, you can apply standard algorithms easily. Also, if you need to return the new size(used elements in the array):
long* end_after_unique = unique(...);
return end_after_unique - array;
std::map only allow a single entry and will sort the items for you automatically. The "second" value in your case is a don't care.
std::map<INT32,INT32> mymap;
mymap[i] = array[i];//inserts if not already present
精彩评论