Create a Vec <BTreeSet <char>> from Vec <Vec <char>>
I am trying to create a set ( Vec<BTreeSet<char>>) vector from Vec<Vec<char>>. Here is my progress:
use std::collections::BTreeSet;
fn main() {
// The data
let transaction_list = [
vec!['A','B','C','D'],
vec!['B','B','C'],
vec!['A','B','B','D']
];
// Successfully created a set from the Vec of Vec. It contains unique chars
let item_set: BTreeSet<char> = transaction_list.iter().flat_map(|t| t).cloned().collect();
// Made the same Vec of Vec. Basically just experimenting with map and collect
let the_same_transaction_list: Vec<Vec<char>> = transaction_list.iter().map(|t| t ).cloned().collect::<Vec<_>>();
// ERROR
let transaction_set: Vec<BTreeSet<char>> = transaction_list
.iter()
.map(|t| t.iter().map(|t| t).cloned().collect() )
.cloned().collect::<Vec<_>>();
}
Error message:
error: the trait `core::iter::FromIterator<char>` is not implemented for the type `&_` [E0277]
.map(|t| t.iter().map(|t| t).cloned().collect() )
^~~~~~~~~
help: see the detailed explanation for E0277
note: a collection of type `&_` cannot be built from an iterator over elements of type `char`
I did not find the right way to make Vec<BTreeSet<char>>out Vec<Vec<char>>. Here's the url of the playground: http://is.gd/WVONHY .
+4
1 answer
The error message is a bit odd. Here's the solution:
let transaction_set: Vec<BTreeSet<_>> =
transaction_list
.iter()
.map(|t| t.iter().cloned().collect())
.collect();
Two major changes:
map(|x| x)pointless. This is a no-op.- I deleted the external one
cloned. The type of call resultmapwill already beBTreeSet. There is no need then to clone it again.
, :
fn cloned<'a, T>(self) -> Cloned<Self>
where Self: Iterator<Item=&'a T>,
T: 'a + Clone
cloned, Item , . BTreeSet s, . , collect char &_ ( - ), cloned. , , , collect. , :
let transaction_set: Vec<_> =
transaction_list
.iter()
.map(|t| -> BTreeSet<_> {t.iter().cloned().collect()})
.cloned().collect();
:
error: type mismatch resolving `<[closure...] as core::ops::FnOnce<(&collections::vec::Vec<char>,)>>::Output == &_`:
expected struct `collections::btree::set::BTreeSet`,
found &-ptr [E0271]
.cloned().collect();
^~~~~~~~
error: no method named `collect` found for type `core::iter::Cloned<core::iter::Map<core::slice::Iter<'_, collections::vec::Vec<char>>, [closure...]>>` in the current scope
.cloned().collect();
^~~~~~~~~
note: the method `collect` exists but the following trait bounds were not satisfied: `core::iter::Cloned<core::iter::Map<core::slice::Iter<'_, collections::vec::Vec<char>>, [closure...]>> : core::iter::Iterator`
, - cloned.
+4