Collections
Array
C++ :
#include <iostream>
#include <array>
using namespace std;
struct Person
{
string name;
int age;
};
int main()
{
array<int,10> arr;
for(int i = 0; i < 10; i++)
{
arr[i] = i;
}
for(auto &x : arr)
{
cout << x << " ";
}
cout << endl;
array<Person,4> persons = {Person{"John", 20}, Person{"Steve", 55},
Person{"Adam", 60}, Person{"Kim", 50}};
for (auto &person : persons)
{
cout << person.name << " , " << person.age << " years old" << endl;
}
return 0;
}
Rust :
struct Person
{
name : &'static str,
age : i32
}
fn main()
{
let mut arr = [0;10];
for i in 0..10
{
arr[i] = i;
}
for x in &arr // same as : for x in arr.iter()
{
print!("{} ", x);
}
println!("");
let persons = [Person{name : "John", age : 20}, Person{name : "Steve", age : 55},
Person{name : "Adam", age : 60}, Person{name : "Kim", age : 50}];
for person in &persons
{
println!("{} , {} years old", person.name, person.age);
}
}
There are two ways to declare an array in rust :
- By specifying the initial value and the number of element of the array : [init_value; N] : this creates an array with N elements, each has the value of init_value
- By listing all elements of the array [element1,element2,element3...], the elements are separated by the commas.
Vector
C++:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a, b;
a.push_back(1);
a.push_back(2);
a.push_back(3);
for(auto &x : a)
{
b.push_back(2*x);
}
for(int i = 0; i < a.size(); i++)
{
cout << "a[" << i << "]=" << a[i] << endl;
}
for(int i = 0; i < a.size(); i++)
{
cout << "2*" << a[i] << " = " << b[i] << endl;
}
return 0;
}
Rust :
fn main()
{
let mut a : Vec<i32> = Vec::new();
let mut b : Vec<i32> = Vec::new();
a.push(1);
a.push(2);
a.push(3);
for x in &a // same as : for x in a.iter()
{
b.push(2*x);
}
for (i,x) in a.iter().enumerate()
{
println!("a[{}] = {}", i, x);
}
for (x,y) in a.iter().zip(b.iter())
{
println!("2*{}={}", x, y);
}
}
In the above program, the vectors are created with Vec::new(), beside this way, vectors can be created with these two following statements, which are similar to the ways of array creation:
- Specifying the initial value and the number of elements in the vector : vec![init_value;N]
- Listing elements of the vectors : vec![element1,element2,....]
The syntax of the loop with 2 vectors in Rust is a bit different from C++. In fact, you can use the same syntax as in C++, which uses a common index variable to access elements of two vectors in the loop. However, idiomatic Rust often uses the zip syntax:
for (x,y) in a.iter().zip(b.iter())
{
println!("2*{}={}", x, y);
}
The zip function joins two arrays into a new array with each element being a pair of elements from the two arrays. By using this technique, the code inside the loop does not need to check for index boundary but still remains safe, so the performance remain the same as C++ programs (C++ programs do not check index boundary by default and are considered unsafe)
Slice
Slice is a part of an array or a vector. C++ does not have slice in its standard collection library, since it can use raw pointers to access any part of an array/vector. Rust has slice, which is effectively a subarray of an original array/vector.
fn main()
{
let mut arr = [0;10];
for i in 0..10
{
arr[i] = i;
}
let sub_arr = &arr[1..4]; // slice that contains element from index 1 to 3
for x in sub_arr.iter()
{
print!("{} ", x);
}
println!("");
}
Map
C++
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string, int> mymap;
mymap["one"] = 1;
mymap["two"] = 2;
mymap["three"] = 3;
mymap["four"] = 4;
int num = mymap["one"];
cout << "one -> " << num << endl;
mymap.erase("one");
for(auto &item: mymap)
{
cout << item.first << "=" << item.second << endl;
}
return 0;
}
Rust:
use std::collections::HashMap;
fn main()
{
let mut mymap = HashMap::new();
mymap.insert("one", 1);
mymap.insert("two", 2);
mymap.insert("three", 3);
mymap.insert("four", 4);
if let Some(num) = mymap.get("one")
{
println!("one -> {}", num);
}
mymap.remove("one");
for (k,v) in &mymap
{
println!("{}={}", k, v);
}
}
Set
C++:
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<string> myset;
myset.insert("one");
myset.insert("two");
myset.insert("three");
myset.insert("four");
myset.erase("one");
if(myset.count("one"))
cout << "'one' is in the set" << endl;
if(myset.count("two"))
cout << "'two' is in the set" << endl;
for(auto &item : myset)
cout << item << endl;
return 0;
}
Rust:
use std::collections::HashSet;
fn main()
{
let mut myset = HashSet::new();
myset.insert("one");
myset.insert("two");
myset.insert("three");
myset.insert("four");
myset.remove("one");
if myset.contains("one") {
println!("'one' is in the set");
}
if myset.contains("two") {
println!("'two' is in the set");
}
for item in &myset {
println!("{}", item);
}
}