0

I would like to sum elements in a vector whose index exists in a hashset.

I assume there is a combination of iterator adaptors I could use to achieve this, but can't seem to figure out what to use. I know I could create a function and use a for loop over the vector, but I want to do the calculation inline and store straight into a variable.

An example of the behaviour I would like:

use std::collections::HashSet;

let v: Vec<u32> = vec![5, 3, 7, 4, 3, 2, 1];
let s: HashSet<u32> = [2, 3, 6].iter().copied().collect();

let actual = v.iter()....
let expected = 12;

assert_eq!(actual, expected);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Michael Hall
  • 2,834
  • 1
  • 22
  • 40
  • 2
    The duplicates [applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=69417692379f315d3ac2f5f5edaa254f). – Shepmaster Nov 13 '19 at 13:56
  • Thanks @Shepmaster . Even though I know this is a duplicate, could you add your code from the playground as an answer for others to see directly on this question? – Michael Hall Nov 13 '19 at 14:00
  • 1
    Sorry, but answers cannot be added to closed questions. – Shepmaster Nov 13 '19 at 14:01

0 Answers0