Created
March 14, 2018 05:59
-
-
Save rust-play/40a9753ca35664d8bd5de48165323aa3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cmp::{Ord, Ordering}; | |
use std::collections::BTreeMap; | |
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)] | |
struct Criteria<T>(Vec<T>); | |
impl<T> From<Vec<T>> for Criteria<T> { | |
fn from(v: Vec<T>) -> Criteria<T> { | |
Criteria(v) | |
} | |
} | |
impl<T: Ord> Ord for Criteria<T> { | |
fn cmp(&self, other: &Self) -> Ordering { | |
for i in 0..(self.0.len().min(other.0.len())) { | |
if self.0[i] < other.0[i] { | |
return Ordering::Less; | |
} else if self.0[i] > other.0[i] { | |
return Ordering::Greater; | |
} | |
} | |
self.0.len().cmp(&other.0.len()) | |
} | |
} | |
fn main() { | |
let criteria: Vec<Criteria<String>> = vec![ | |
vec!["test", "ing"], | |
vec!["test"], | |
vec!["dost", "o"], | |
vec!["tost"], | |
] | |
.into_iter() | |
.map(|vec| Criteria(vec | |
.into_iter() | |
.map(|s| s.to_owned()) | |
.collect() | |
)).collect(); | |
println!("before: {:?}", criteria); | |
let mut map: BTreeMap<Criteria<String>, usize> = BTreeMap::new(); | |
for (index, criterion) in criteria.into_iter().enumerate() { | |
map.insert(criterion, index); | |
} | |
println!("sorted: {:?}", map.keys()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment