Finding the maximum allowable value for type T

I implement merge sort, which sorts an array of type T In my merge method, the algorithm requires the last element of the left and right list to be positive infinity . How can I get the maximum value that a given data type can store?

 fn merge<T: PartialOrd + Copy + std::fmt::Debug>(p: usize, q: usize, r: usize, array: &mut Vec<T>) { let left_size: usize = q - p; let right_size: usize = r - q; let mut left: Vec<T> = Vec::new(); let mut right: Vec<T> = Vec::new(); for i in 0..left_size { left.push(array[p + i]); } for i in 0..right_size { right.push(array[q + i]); } left.push(T::max_value()); //where I would put the max value right.push(T::max_value()); //where I would put the max value let mut i: usize = 0; let mut j: usize = 0; for k in p..r { if left[i] <= right[j] { array[k] = left[i]; i += 1; } else { array[k] = right[j]; j += 1; } } } 
+5
source share
2 answers

As far as I know, there is currently no way to do this with the standard library. One way to solve it is to make your own trait, add another trait attached to the merge , and implement your trait for the expected types.

Implementing a specific attribute for u32 will then return std::u32::MAX , etc. for other types.

Here is a discussion from the beginning of this year .

As oli_obk - ker pointed out below , the num box already has this feature: Bounded .

+4
source

For a common upper bound, you can also wrap the type in an enumeration:

 #[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] enum UpperBounded<T> { Value(T), Max, } 

The derived order is documented to sort Value(_) to Max .

UpperBounded<T> can then be used for the left and right vectors.

+1
source

Source: https://habr.com/ru/post/1274220/


All Articles