rust vs c++

  • C++ 迭代器 vs Rust Iterator trait
// c++ 
const vector<int> v{1,2,3,4,5};
auto ret = -1;
for( auto i = 0; i < v.size(); i++){
    if (v[i] == 3){
        ret = i;
        break;
    }
    // do some complicated logic
}

return ret; // return 2

// c++ using std find
auto it = std::find(v.begin(), v.end(), [](int cur){
    if (cur == 3)
        return true;
    ... // do some complicated logic
    return false;
})
return it == v.end() ? it-v.begin() : -1; // return 2
// rust equivalent code with nicer readability
vec![1,2,3,4,5].into_iter().enumerate().try_fold(-1, |acc, (i, inner)| {
    if inner == 3 {
        Err(i as i32)
    }else {
        // do some complicated logic
        Ok(acc)
    }
}).unwrap_or_else(|e|e) // return 2
  • rust HashMap vs C++ unordered_map
// c++
std::unordered_map<int, int> m;
// insert data
m[1]=2;
// get data
const auto r = m[1];
// do something if exist or else
if(m.count(1))
    m[1]=3;
else
    m[1]=4;
// rust
std::collections::hashmap<int, int> m; // long declaration
// insert data
m.insert(1, 2);
// get data
let val = m.get(1).unwrap_or(...);
// do something if exist or else
m.entry(1).and_modify(|inner|*inner=3).or_insert(4); 
m.get_mut(&1).and_then(|inner| *inner=3); 
// c++, terrible experience to have customized key of unordered_map
struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }    
};

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
    using std::size_t;
    using std::hash;
    using std::string;

    return ((hash<string>()(k.first)
             ^ (hash<string>()(k.second) << 1)) >> 1)
             ^ (hash<int>()(k.third) << 1);
  }
};

std::unordered_map<Key,std::string,KeyHasher> m6 = {
  { {"John", "Doe", 12}, "example"},
  { {"Mary", "Sue", 21}, "another"}
};
// rust
#[derive(Hash, Eq, PartialEq)]
struct A(String, String, i64);
let mut m = std::collections::HashMap::new(); // easy declaration
m.insert(A("a".to_string(), "b".to_string(), 3), 4);
  • 链表
// c++, neat and straight-forward
struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int maxDepth(TreeNode *root)
{
    return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1; // quite straight-forward
}
// rust
pub struct TreeNode {
   pub val: i32,
   pub left: Option<Rc<RefCell<TreeNode>>>,
   pub right: Option<Rc<RefCell<TreeNode>>>,
}
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    root.map_or(0, |n| {
        1 + Self::max_depth(n.borrow().left.clone())
            .max(Self::max_depth(n.borrow().right.clone()))    // um....at first glance, why borrow() ? 
    })
}
  • priority_queue
// c++
auto cmp = [](int a, int b) { return a > b; }; 
std::priority_queue<int, std::vector<int>, decltype(cmp)> q(cmp); // min-heap with lambda style
// rust
// built-in binary heap doesn't support. But there is an external crate, `binary-heap-plus`, would do the trick
// custom-sort heap
let heap = BinaryHeap::from_vec_cmp(vec![1,5,3], FnComparator(|a: &i32, b: &i32| b.cmp(a)));
// rust, workaround to sort by closure
let mut v = vec![];
v.push(2);
v.push(1);
v.push(3);
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
  • Rust 字符串
// c++
auto s = "abc"s;
auto c = s[0]; // okay
// rust
let s = "abc".to_string();
let c = s[0]; // compiler error, wait what ?
  • 三元运算符
// c++
const auto a = x>0 ? 1 : 2; // as usual
// rust
let a = if x>0 {1} else {2}; // barely acceptable
  • 语句压缩
// c++
for(auto i = 0 ; i < v.size(); i++)
    x++, y--, z+=1; // save lines
// rust, extra lines, extra typing
for i in 0..v.size() {
    x++; 
    y--; 
    z++;
}
  • 运算符增减
// c++, 
if ( auto a = ++i; --a > 0 )
    // do something
// rust, always explicit
i += 1;
let a = i;
a -= 1;
if (a > 0) {
    // do something
}
  • C++ std::exchange VS Rust std::mem::replace。
// concept
temp = a; // reserve the old value
a = b;    // update value
c = temp; // assign old value to other var
// c++ equivalent code
c = std::exchange(a, b);
// rust equivalent code
c = std::mem::replace(&mut a, b);
// c++
c = std::exchange(a, a + 5); // Okay
// rust
c = std::mem::replace(&mut a, a+5); // compiler error, wait what ?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值