Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to compare 2 vectors or strings element by element?

Tags:

rust

What's the best way to compare 2 vectors or strings element by element in Rust, while being able to do processing on each pair of elements? For example if you wanted to keep count of the number of differing elements. This is what I'm using:

let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
    if x != y {
        diff_count += 1i32;
    }
}

Is that the correct way or is there something more canonical?

like image 526
anderspitman Avatar asked Apr 08 '15 01:04

anderspitman


People also ask

How do you compare two vectors?

A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.

How do you compare vector strings?

Comparing two vectors using operator == std::vector provides an equality comparison operator==, it can be used to compare the contents of two vectors. For each element in the vector it will call operator == on the elements for comparisons.

How do you compare two vectors for equality?

C++ Vector Library - operator== Function The C++ function std::vector::operator== tests whether two vectors are equal or not. Operator == first checks the size of both container, if sizes are same then it compares elements sequentially and comparison stops at first mismatch.

How do you compare elements in C++?

C++ has in-built compare() function in order to compare two strings efficiently. The compare() function compares two strings and returns the following values according to the matching cases: Returns 0, if both the strings are the same.


2 Answers

To get the count of matching elements, I'd probably use filter and count.

fn main() {
    let a = "Hello";
    let b = "World";

    let matching = a.chars().zip(b.chars()).filter(|&(a, b)| a == b).count();
    println!("{}", matching);

    let a = [1, 2, 3, 4, 5];
    let b = [1, 1, 3, 3, 5];

    let matching = a.iter().zip(&b).filter(|&(a, b)| a == b).count();
    println!("{}", matching);
}
like image 145
Shepmaster Avatar answered Nov 15 '22 16:11

Shepmaster


If you wanted to use @Shepmaster's answer as the basis of an assertion to be used in a unit test, try this:

fn do_vecs_match<T: PartialEq>(a: &Vec<T>, b: &Vec<T>) -> bool {
    let matching = a.iter().zip(b.iter()).filter(|&(a, b)| a == b).count();
    matching == a.len() && matching == b.len()
}

Of course, be careful when using this on floats! Those pesky NaNs won't compare, and you might want to use a tolerance for comparing the other values. And you might want to make it fancy by telling the index of the first nonmatching value.

like image 4
Paul Chernoch Avatar answered Nov 15 '22 15:11

Paul Chernoch