第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何編寫一個返回對自身引用的迭代器?

如何編寫一個返回對自身引用的迭代器?

慕沐林林 2019-07-31 10:36:23
如何編寫一個返回對自身引用的迭代器?我無法表達Iterator實現(xiàn)的返回值的生命周期。如何在不更改迭代器的返回值的情況下編譯此代碼?我希望它返回一個引用的向量。很明顯,我沒有正確使用生命周期參數(shù),但在嘗試了我放棄的各種方法之后,我不知道如何處理它。use std::iter::Iterator;struct PermutationIterator<T> {     vs: Vec<Vec<T>>,     is: Vec<usize>,}impl<T> PermutationIterator<T> {     fn new() -> PermutationIterator<T> {         PermutationIterator {             vs: vec![],             is: vec![],         }     }     fn add(&mut self, v: Vec<T>) {         self.vs.push(v);         self.is.push(0);     }}impl<T> Iterator for PermutationIterator<T> {     type Item = Vec<&'a T>;     fn next(&mut self) -> Option<Vec<&T>> {         'outer: loop {             for i in 0..self.vs.len() {                 if self.is[i] >= self.vs[i].len() {                     if i == 0 {                         return None; // we are done                     }                     self.is[i] = 0;                     self.is[i - 1] += 1;                     continue 'outer;                 }             }             let mut result = vec![];             for i in 0..self.vs.len() {                 let index = self.is[i];                 result.push(self.vs[i].get(index).unwrap());             }             *self.is.last_mut().unwrap() += 1;             return Some(result);         }     }}fn main() {     let v1: Vec<_> = (1..3).collect();     let v2: Vec<_> = (3..5).collect();     let v3: Vec<_> = (1..6).collect();     let mut i = PermutationIterator::new();     i.add(v1);     i.add(v2);     i.add(v3);     loop {         match i.next() {             Some(v) => {                 println!("{:?}", v);             }             None => {                 break;             }         }     }}(游樂場鏈接)error[E0261]: use of undeclared lifetime name `'a`   --> src/main.rs:23:22    | 23 |     type Item = Vec<&'a T>;    |                      ^^ undeclared lifetime
查看完整描述

3 回答

?
慕村225694

TA貢獻1880條經(jīng)驗 獲得超4個贊

據(jù)我所知,你想要迭代器將引用向量返回給自己,對吧?不幸的是,在Rust中是不可能的。

這是減少的Iterator特性:

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Item>;}

請注意,和之間沒有生命周期連接。這意味著該方法不能將引用返回到迭代器本身。你只是無法表達返回引用的生命周期。這基本上是你找不到指定正確生命周期的方法的原因 - 它看起來像這樣:&mut selfOption<Item>next()

fn next<'a>(&'a mut self) -> Option<Vec<&'a T>>

除了這不是一個有效next()Iterator特質(zhì)方法。

這些迭代器(可以將引用返回到它們自己的迭代器)稱為流迭代器。如果你愿意,你可以在這里,這里這里找到更多。

更新。但是,您可以從迭代器返回對其他結(jié)構(gòu)的引用 - 這就是大多數(shù)集合迭代器的工作方式。它可能看起來像這樣:

pub struct PermutationIterator<'a, T> {
    vs: &'a [Vec<T>],
    is: Vec<usize>}impl<'a, T> Iterator for PermutationIterator<'a, T> {
    type Item = Vec<&'a T>;

    fn next(&mut self) -> Option<Vec<&'a T>> {
        ...
    }}

注意'a現(xiàn)在如何在impl塊上聲明生命周期。可以這樣做(事實上是必需的)因為你需要在結(jié)構(gòu)上指定生命周期參數(shù)。然后你可以使用相同的'ain Itemnext()return類型。同樣,這就是大多數(shù)集合迭代器的工作方式。


查看完整回答
反對 回復(fù) 2019-07-31
?
慕無忌1623718

TA貢獻1744條經(jīng)驗 獲得超4個贊

它可以從其他東西中產(chǎn)生借來的價值。這是與實現(xiàn)VecIter:在Vec擁有值,并且在Iter剛能中產(chǎn)生的引用的包裝Vec。

這是一個實現(xiàn)您想要的設(shè)計。迭代器就像VecIter,和實際擁有值的其他容器一樣。

use std::iter::Iterator;struct PermutationIterator<'a, T: 'a> {
    vs : Vec<&'a [T]>,
    is : Vec<usize>}impl<'a, T> PermutationIterator<'a, T> {
    fn new() -> PermutationIterator<'a, T> { ... }

    fn add(&mut self, v : &'a [T]) { ... }}impl<'a, T> Iterator for PermutationIterator<'a, T> {
    type Item = Vec<&'a T>;
    fn next(&mut self) -> Option<Vec<&'a T>> { ... }}fn main() {
    let v1 : Vec<i32> = (1..3).collect();
    let v2 : Vec<i32> = (3..5).collect();
    let v3 : Vec<i32> = (1..6).collect();

    let mut i = PermutationIterator::new();
    i.add(&v1);
    i.add(&v2);
    i.add(&v3);

    loop {
        match i.next() {
            Some(v) => { println!("{:?}", v); }
            None => {break;}
        }
    }}

(操場)


與您的初始問題無關(guān)。如果這只是我,我會確保所有借來的載體都是一次性的。我們的想法是刪除重復(fù)調(diào)用add并直接傳遞構(gòu)造中所有借用的向量:

use std::iter::{Iterator, repeat};struct PermutationIterator<'a, T: 'a> {
    ...}impl<'a, T> PermutationIterator<'a, T> {
    fn new(vs: Vec<&'a [T]>) -> PermutationIterator<'a, T> {
        let n = vs.len();
        PermutationIterator {
            vs: vs,
            is: repeat(0).take(n).collect(),
        }
    }}impl<'a, T> Iterator for PermutationIterator<'a, T> {
    ...}fn main() {
    let v1 : Vec<i32> = (1..3).collect();
    let v2 : Vec<i32> = (3..5).collect();
    let v3 : Vec<i32> = (1..6).collect();
    let vall: Vec<&[i32]> = vec![&v1, &v2, &v3];

    let mut i = PermutationIterator::new(vall);}

(操場)

編輯:將迭代器設(shè)計改為采用Vec<&'a [T]>而不是a Vec<Vec<&'a T>>。使用ref容器比構(gòu)建refs容器更容易。)


查看完整回答
反對 回復(fù) 2019-07-31
?
慕標5832272

TA貢獻1966條經(jīng)驗 獲得超4個贊

正如其他答案中所提到的,這被稱為流式迭代器,它需要Rust的不同保證Iterator。提供此類功能的一個箱子恰當?shù)胤Q為流式迭代器,它提供了StreamingIterator特性。

以下是實現(xiàn)特征的一個示例:

extern crate streaming_iterator;use streaming_iterator::StreamingIterator;struct Demonstration {
    scores: Vec<i32>,
    position: usize,}// Since `StreamingIterator` requires that we be able to call// `advance` before `get`, we have to start "before" the first// element. We assume that there will never be the maximum number of// entries in the `Vec`, so we use `usize::MAX` as our sentinel value.impl Demonstration {
    fn new() -> Self {
        Demonstration {
            scores: vec![1, 2, 3],
            position: std::usize::MAX,
        }
    }

    fn reset(&mut self) {
        self.position = std::usize::MAX;
    }}impl StreamingIterator for Demonstration {
    type Item = i32;

    fn advance(&mut self) {
        self.position = self.position.wrapping_add(1);
    }

    fn get(&self) -> Option<&Self::Item> {
        self.scores.get(self.position)
    }}fn main() {
    let mut example = Demonstration::new();

    loop {
        example.advance();
        match example.get() {
            Some(v) => {
                println!("v: {}", v);
            }
            None => break,
        }
    }

    example.reset();

    loop {
        example.advance();
        match example.get() {
            Some(v) => {
                println!("v: {}", v);
            }
            None => break,
        }
    }}

不幸的是,在實現(xiàn)RFC 1598的通用關(guān)聯(lián)類型(GAT)之前,流式迭代器將受到限制。


查看完整回答
反對 回復(fù) 2019-07-31
  • 3 回答
  • 0 關(guān)注
  • 694 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號