sách gpt4 ai đã đi

collections - 从 Vec<>> 创建一个 Vec<>>

In lại 作者:行者123 更新时间:2023-11-29 07:54:37 30 4
mua khóa gpt4 Nike

Tôi đang cố gắng Vec<>> 创建一个集合向量 ( Vec<>> ) .这是我目前的进展:

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 = 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<>> = transaction_list.iter().map(|t| t ).cloned().collect::>();

// ERROR
let transaction_set: Vec<>> = transaction_list
.iter()
.map(|t| t.iter().map(|t| t).cloned().collect() )
.cloned().collect::>();
}

错误信息是:

error: the trait `core::iter::FromIterator` 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`

我还没有找到制作 Vec<>> 的正确方法来自 Vec<>> .这是 Playground 网址:http://is.gd/WVONHY .

1 Câu trả lời

错误信息有点奇怪。这是解决方案:

let transaction_set: Vec> =
transaction_list
.iter()
.map(|t| t.iter().cloned().collect())
.collect();

两个主要变化是:

  1. map(|x| x) 毫无意义。这是一个空操作。
  2. 我删除了外部dòng vô tính. map 调用的结果类型已经是 BTreeSet。无需再次克隆它。

后者解决了你的问题,所以让我们看看定义:

fn cloned<'a, T>(self) -> Cloned 
where Self: Iterator,
T: 'a + Clone

为了能够调用dòng vô tính,迭代器Item 必须是对可克隆对象的Tài liệu tham khảo。但是,您正在尝试迭代不是引用的 BTreeSet。编译器选择告诉您无法将 char 的内部迭代器 collect 转换为 &_(对某种类型的引用),这然后将满足调用 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,)>>::Output == &_`:
expected struct `collections::btree::set::BTreeSet`,
found &-ptr [E0271]
.cloned().collect();
^~~~~~~~

error: no method named `collect` found for type `core::iter::Cloned<>>, [closure...]>>` in the current scope
.cloned().collect();
^~~~~~~~~
note: the method `collect` exists but the following trait bounds were not satisfied: `core::iter::Cloned<>>, [closure...]>> : core::iter::Iterator`

这有助于强调问题是由 cloned 的外部使用引起的。

关于collections - 从 Vec<>> 创建一个 Vec<>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244518/

30 4 0
Bài viết được đề xuất: java - 如何在项目中找到绝对路径
Bài viết được đề xuất: php - ON DUPLICATE KEY UPDATE 上的 SQL 语法错误
Bài viết được đề xuất: java - 尝试使用参数中的变量在Java中画一个圆
Bài viết được đề xuất: php - 在 while 循环中使用 JOIN sql 查询
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com