如何在不使用循环(如下所示)的情况下[91, 55, 77, 91]计算具有特定值(例如91)的向量(例如)中的元素?
fn count_eq(vec: &Vec<i64>, num: i64) -> i64 {
let mut counter = 0;
for i in vec {
if *i == num {
counter += 1;
}
}
return counter;
}
fn main() {
let v = vec![91, 55, 77, 91];
println!("count 91: {}", count_eq(&v, 91));
}
Run Code Online (Sandbox Code Playgroud) 我想将a转换Vec<T>为Vec<U>where T某种原语,并且U是一种新类型T:struct U(T).
我试过这样的事情:
struct Foo(u32);
fn do_something_using_foo(buffer: &mut Vec<Foo>) {}
fn main() {
let buffer: Vec<u32> = vec![0; 100];
do_something_using_foo(&mut buffer as Vec<Foo>);
}
Run Code Online (Sandbox Code Playgroud)
我不想复制矢量,我想u32在newtype中包装字段Foo.
这给出了错误:
error[E0308]: mismatched types
--> main.rs:8:28
|
8 | do_something_using_foo(&mut buffer as Vec<Foo>);
| ^^^^^^^^^^^^^^^^^^^^^^^ expected mutable reference, found struct `std::vec::Vec`
|
= note: expected type `&mut std::vec::Vec<Foo>`
found type `std::vec::Vec<Foo>`
= help: try with `&mut &mut buffer as …Run Code Online (Sandbox Code Playgroud) 我想替换内部match语句并为字母表用尽时的所有值工作.我知道我可以自己写,但我想使用内置函数.
fn convert(inp: u32, out: u32, numb: &String) -> Result<String, String> {
match isize::from_str_radix(numb, inp) {
Ok(a) => match out {
2 => Ok(format!("{:b}", a)),
8 => Ok(format!("{:o}", a)),
16 => Ok(format!("{:x}", a)),
10 => Ok(format!("{}", a)),
0 | 1 => Err(format!("No base lower than 2!")),
_ => Err(format!("printing in this base is not supported")),
},
Err(e) => Err(format!(
"Could not convert {} to a number in base {}.\n{:?}\n",
numb, inp, e
)),
}
}
Run Code Online (Sandbox Code Playgroud) 我将使用10 ^ 6 +元素对多个向量进行元素乘法.这在标题中被标记为我的代码中最慢的部分之一,所以我该如何改进它?
/// element-wise multiplication for vecs
pub fn vec_mul<T>(v1: &Vec<T>, v2: &Vec<T>) -> Vec<T>
where
T: std::ops::Mul<Output = T> + Copy,
{
if v1.len() != v2.len() {
panic!("Cannot multiply vectors of different lengths!")
}
let mut out: Vec<T> = Vec::with_capacity(v1.len());
for i in 0..(v1.len()) {
out.push(v1[i] * v2[i]);
}
out
}
Run Code Online (Sandbox Code Playgroud) 我想实现一个函数,它接受不可变的&Vec引用,制作副本,对值进行排序并打印它们。
这是主要代码。
trait Foo {
fn value(&self) -> i32;
}
struct Bar {
x: i32,
}
impl Foo for Bar {
fn value(&self) -> i32 {
self.x
}
}
fn main() {
let mut a: Vec<Box<dyn Foo>> = Vec::new();
a.push(Box::new(Bar { x: 3 }));
a.push(Box::new(Bar { x: 5 }));
a.push(Box::new(Bar { x: 4 }));
let b = &a;
sort_and_print(&b);
}
Run Code Online (Sandbox Code Playgroud)
我能够让它发挥作用的唯一方法就是这个
fn sort_and_print(v: &Vec<Box<dyn Foo>>) {
let mut v_copy = Vec::new();
for val in v {
v_copy.push(val);
} …Run Code Online (Sandbox Code Playgroud) 我需要类似的东西:
fn my_convert<T, U>(v: &Vec<U>)->Vec<T>{
v.iter().map(|&t|t).collect()
}
Run Code Online (Sandbox Code Playgroud)
当然,我认为只有内置数字类型的向量可以传递给函数。
编译器告诉我需要为 Vec 提供 FromIterator 特征
该特征
std::iter::FromIterator<U>未针对 `std::vec::Vec 实现
然后,我添加了
impl<T, U> std::iter::FromIterator<U> for Vec<T>{
fn from_iter<I>(iter:I)->Self where I: IntoIterator<Item=U>{
Vec::<T>::new() // just for test
}
}
Run Code Online (Sandbox Code Playgroud)
std::iter::FromIterator<_>type 的特征的冲突实现std::vec::Vec<_>:注意:板条箱中的冲突实现alloc: - impl std::iter::FromIterator for std::vec::Vec;rustc(E0119)
众所周知,在C++中,这种转换是直接且直观的。我是 Rust 的初学者。我不知道如何定义上面这样的函数。我什至不知道它是否可以在 Rust 中实现,因为泛型类型特征的复杂性。
谢谢!
我正在学习 Rust 中的字符串。我想实现函数来计算字符串列表中的长公共前缀。
我的代码
impl Solution {
pub fn get_common_prefix(s1: &String, s2: &String) -> String {
let mut idx: usize = 0;
if s1.len() > s2.len() {
std::mem::swap(&mut s1, &mut s2);
}
while idx < s1.len() && s1.chars().nth(idx) == s2.chars().nth(idx) {
idx += 1;
}
return s1[0..idx].to_string();
}
pub fn longest_common_prefix(mut strs: Vec<String>) -> String {
strs.sort();
let mut longest_pref = strs[0];
for i in 0..strs.len() {
longest_pref = Self::get_common_prefix(&longest_pref, &strs[i]);
}
return longest_pref;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个错误。您能帮忙修复一下吗?
Line 5, Char …Run Code Online (Sandbox Code Playgroud) 这是一个人为的例子,但我相信如果我能够做到这一点,我可以将它应用于我的具体案例.
extern crate num;
extern crate rayon;
use rayon::prelude::*;
use num::Float;
fn sqrts<T: Float>(floats: &Vec<T>) -> Vec<T> {
floats.par_iter().map(|f| f.sqrt()).collect()
}
fn main() {
let v = vec![1.0, 4.0, 9.0, 16.0, 25.0];
println!("{:?}", sqrts(&v));
}
Run Code Online (Sandbox Code Playgroud)
编译时出现这种错误,"方法par_iter存在,但不满足以下特征限制:&std::vec::Vec<T> : rayon::par_iter::IntoParallelIterator".如果我使用iter代替par_iter或如果我切换到使用f32或f64代替通用,代码工作正常.
我能做些什么才能par_iter在泛型载体上使用?该IntoParallelIterator特征是否意味着由最终用户实施?我该怎么做呢?
我正在实现一个合并排序,它将对一个类型的数组进行排序T.在我的merge方法中,算法要求左右列表的最后一个元素为正无穷大.如何获得给定数据类型可以容纳的最大值?
fn merge<T: PartialOrd + Copy + std::fmt::Debug>(p: usize, q: usize, r: usize, array: &mut Vec<T>) {
let left_size: usize = q - p;
let right_size: usize = r - q;
let mut left: Vec<T> = Vec::new();
let mut right: Vec<T> = Vec::new();
for i in 0..left_size {
left.push(array[p + i]);
}
for i in 0..right_size {
right.push(array[q + i]);
}
left.push(T::max_value()); //where I would put the max value
right.push(T::max_value()); //where I would put …Run Code Online (Sandbox Code Playgroud) 我正在尝试解决Rust Book 本章末尾的一个练习。
这是一个代码示例:
fn mean(v: &Vec<i32>) -> f64 {
let mut sum = 0.0;
let mut count = 0.0;
for val in v {
sum += &f64::from(val);
count += 1.0;
}
sum / count
}
fn main() {
let v = vec![1, 2, 3, 4];
println!("The mean is {}", mean(&v));
}
Run Code Online (Sandbox Code Playgroud)
错误是:
fn mean(v: &Vec<i32>) -> f64 {
let mut sum = 0.0;
let mut count = 0.0;
for val in v {
sum += &f64::from(val);
count …Run Code Online (Sandbox Code Playgroud)