// 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"}
};
// 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 ?