gpt4 book ai didi

memory-management - 有没有一种方法可以在不将每个元素推送到字符串的情况下在使用它获取字符串的同时在空白处加入 BTreeSet?

转载 作者:行者123 更新时间:2023-11-29 08:29:13 25 4
gpt4 key购买 nike

有没有办法加入BTreeSet在使用空格的同时使用它来获取每个元素由空格分隔的字符串,而不是通过遍历每个元素并推送到一个字符串?

我的集合可能非常大,最多可能有 10GB,所以我想限制内存使用量。

type `std::collections::BTreeSet<std::vec::Vec<u8>>`

我正在使用 bio crate用于对 DNA 字符串进行反向恭维,takes and returns a Vec<u8> (或者至少返回 Vec<u8> )所以为了避免在某些步骤中来回转换我想保持它们原样。

这是一个例子:

let dna_pieces = std::fs::read_to_string(path_dna_file).expect("Unable to read file");
let dna_pieces = dna_pieces.split(" ");

let mut dna_pieces_set = BTreeSet::new();

// first adds a small set to the tree
for dna_piece in dna_pieces {
let dna_bytes = species_kmer.to_owned().into_bytes();
dna_pieces_set.insert(dna_bytes);
}

// then adds a bigger other set to the same tree
let dna_pieces_big_list = std::fs::read_to_string(path_dna_file_big).expect("Unable to read file");
let dna_pieces_big_list = dna_pieces_big_list.split(" ");
for dna_piece in dna_pieces_big_list {
let dna_bytes = dna_piece.to_owned().into_bytes();
let dna_bytes_to_rev = dna_piece.to_owned().into_bytes();
let reverse_complement = bio::alphabets::dna::revcomp(dna_bytes_to_rev);
if !dna_pieces_set.contains(&reverse_complement) {
dna_pieces_set.insert(dna_bytes);
}
}

// format the treeset into a string output_unique_dna_pieces...

std::fs::write(path_unique_dna_pieces, output_unique_dna_pieces).expect("Unable to write file");

最佳答案

这是不可能的。如果你想避免两次分配集合的全部内容,你真的有两个选择:

  1. 切换到 HashSet,这样您就可以使用它的 drain 方法。不幸的是,BTreeSet 尚不存在此方法。

    let mut output = Vec::new(); // use with_capacity if you know an upper bound on the size
    for x in hash_set.drain() {
    output.extend_from_slice(&x);
    output.push(b' '); // add the space
    }
  2. 直接写入文件而不是创建临时数据结构。使用 BufWriter 来减少 IO 调用。

    let buffer = File::create("filename.txt")?;
    let mut writer = BufWriter::new(buffer);
    for dna_piece in dna_pieces_set.iter() {
    writer.write(dna_piece)?;
    writer.write(b" ")?; // add the space
    }

关于memory-management - 有没有一种方法可以在不将每个元素推送到字符串的情况下在使用它获取字符串的同时在空白处加入 BTreeSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54251695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com