Vector & List
Linear data structures.
C++
Rust
Java
vector<int> v = {5, 4, 3, 2, 1};
list<int> l = {10, 9, 8, 7, 6};
// sort the two
sort(v.begin(), v.end());
l.sort(); // use container specific sort
// print them out
copy(v.begin(), v.end(), ostream_iterator<int>(cout, ","));
copy(l.begin(), l.end(), ostream_iterator<int>(cout, ","));
let v = vec![5, 4, 3, 2, 1];
let mut l = LinkedList::new();
l.push_back(10);
l.push_back(9);
l.push_back(8);
l.push_back(7);
l.push_back(6);
// sort the two
v.sort();
// unfortunately there is no way
// to directly sort a LinkedList
// print them out
for i in v.iter() {
print!("{},", i);
}
for i in l.iter() {
print!("{},", i);
}
List<Integer> v =
new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1));
List<Integer> l =
new LinkedList<>(Arrays.asList(10, 9, 8, 7, 6));
// sort the two
Collections.sort(v);
Collections.sort(l);
// print them out
for(Integer i : v) {
System.out.print(i);
System.out.print(',');
}
for(Integer i : l) {
System.out.print(i);
System.out.print(',');
}
C++11 added brace-initialization to the language and greatly simplified the initialization of conainters. Rust has this
through a macro for Vec
, but lacks it for LinkedList
. Java does not provide any type of
initialization. The easiest way is to leverage Arrays.asList()
.
Sorting is different across the board. In Java a generic algorithm is used to operate on the two containers. In C++
one container has a specialized method, while the other dose not. A generic algorithm can be used for both; however, it
is always a good idea to use class methods when they are available. Rust has no way to sort a LinkedList