感谢你们。我发现我无法在互联网上发布我的问题。
不过,这对我确实很有帮助。
我有一个文件,需要逐行读取并分成两个句子,并用“=”分隔。我正在尝试使用迭代器,但我找不到如何在split. 文档说std::str::Split实现了该特征,但我仍然不知道如何使用它。
use std::{
fs::File,
io::{prelude::*, BufReader},
};
fn example(path: &str) {
for line in BufReader::new(File::open(path).expect("Failed at opening file.")).lines() {
let words = line.unwrap().split("="); //need to make this an iterable
}
}
Run Code Online (Sandbox Code Playgroud)
我如何使用我知道已经实现为 split 之类的特征?
我在 Rust 书中遇到了下面的例子。
for &item in list.iter() {
if item > largest {
largest = item;
}
}
Run Code Online (Sandbox Code Playgroud)
我想这意味着list.iter()返回对列表中元素的引用,&item但是在将其与最大数字进行比较时,为什么我们不使用*item?&item另外,当我将第一行中的to更改为时,编译器item强制我在第二行和第三行中使用。*item
我在网上看到了另一个例子。
(0..).map(|x| x * x)
.take_while(|&x| x <= limit)
.filter(|x| is_even(*x))
Run Code Online (Sandbox Code Playgroud)
这里的闭包take_while接受&x但直接使用x,但闭包filter接受x而不引用但传递*x给is_even。
那么这在 Rust 中是如何工作的呢?
我想定义一个函数,它应该允许我返回一系列结构实例上的迭代器。
我已经为标准类型尝试了相同的功能,例如 usize (请参阅简化的代码示例)并且这有效(尽管有点尴尬)。我无法在我想到的场景中使用标准类型,因此这对解决方案没有帮助,但它帮助我理解这里存在某种问题。
#[derive(Debug)]
struct MyThing();
fn main() {
let good = 0usize..=10usize;
// ALSO WORKS for thing in *good.start()..=*good.end() {
for thing in 0usize..=10usize {
dbg!(thing);
}
dbg!(good);
let bad = MyThing()..=MyThing();
for thing in *bad.start()..=*bad.end() {
dbg!(thing);
}
dbg!(bad);
}
Run Code Online (Sandbox Code Playgroud)
$ cargo --version
cargo 1.35.0 (6f3e9c367 2019-04-04)
$ cargo build
Compiling huh v0.1.0 (huh)
error[E0277]: the trait bound `MyThing: std::iter::Step` is not satisfied
--> src/main.rs:13:18
|
13 | for thing in *bad.start()..=*bad.end() {
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait …Run Code Online (Sandbox Code Playgroud) 我想在对每个级别上的兄弟节点进行排序时,一个接一个地懒惰地消耗文件树的节点。
在 Python 中,我会使用同步生成器:
def traverse_dst(src_dir, dst_root, dst_step):
"""
Recursively traverses the source directory and yields a sequence of (src, dst) pairs;
"""
dirs, files = list_dir_groom(src_dir) # Getting immediate offspring.
for d in dirs:
step = list(dst_step)
step.append(d.name)
yield from traverse_dst(d, dst_root, step)
for f in files:
dst_path = dst_root.joinpath(step)
yield f, dst_path
Run Code Online (Sandbox Code Playgroud)
在 Elixir 中,一个(惰性)流:
def traverse_flat_dst(src_dir, dst_root, dst_step \\ []) do
{dirs, files} = list_dir_groom(src_dir) # Getting immediate offspring.
traverse = fn d ->
step = dst_step …Run Code Online (Sandbox Code Playgroud) 我试图了解 range::views::zip 在 range-v3 中如何工作。据我所知,它是一个范围,允许通过创建不同范围中的元素元组来在一个循环中迭代多个范围。
\n\nstd::vector<int> v1 = {0, 1, 2};\nstd::vector<char> v2 = {'a', 'b', 'c'};\n\n\nauto zip = ranges::views::zip(v1,v2);\n// zip(v1,v2) = [(0,a), (1,b), (2,c)]\n\nranges::actions::sort(zip);\nstd::sort(std::begin(zip), std::end(zip));\nRun Code Online (Sandbox Code Playgroud)\n\n使用排序ranges::actions工作正常,但std::sort无法编译并给出以下错误
/usr/include/c++/9.3.0/bits/stl_algobase.h:151: error: no matching function for call to \xe2\x80\x98swap(concepts::return_t<ranges::common_pair<int&, double&>, void>, concepts::return_t<ranges::common_pair<int&, double&>, void>)\xe2\x80\x99\n 151 | swap(*__a, *__b);\n | ~~~~^~~~~~~~~~~~\nRun Code Online (Sandbox Code Playgroud)\n\n为什么会发生这种情况?
\n\n我还尝试同时删除两个容器中的元素。ranges::actions::unique无法编译并出现以下错误:
/home/jjcasmar/projects/cpfsofaplugin/src/CPFSofaPlugin/minimalExample.cpp:27: error: no match for call to \xe2\x80\x98(const ranges::actions::action_closure<ranges::actions::unique_fn>) (ranges::zip_view<ranges::ref_view<std::vector<int, std::allocator<int> > >, ranges::ref_view<std::vector<double, std::allocator<double> > > >&)\xe2\x80\x99\n 27 | …Run Code Online (Sandbox Code Playgroud) 在不借助 boost.iterator 等库的帮助下创建 C++20 之前的新迭代器时,有必要指定类型别名difference_type、value_type、pointer和。
根据cppreference ,对于 C++20,只需要指定和referenceiterator_categorydifference_typevalue_type这很棒!但是为什么这 3 个别名有默认值呢?
有两件事我不明白(其中一件事在我看来像是一个疏忽):
value_type为什么和没有默认值difference_type?使用类似的东西std::remove_reference_t<reference>作为默认值难道没有意义吗value_type?作为随机访问迭代器的默认设置difference_type,使用采用两个迭代器的运算符的结果类型可以说是有意义的-。contiguous_iterator_tag. 就像与input_iterator_tagvsforward_iterator_tag一样,我不明白编译器如何正确区分连续迭代器和随机访问迭代器,我想这就是它显然从不选择的原因contiguous_iterator_tag。这是故意的吗?将输入迭代器错误分类为前向迭代器似乎也有些危险,那么为什么不要求程序员自己指定此别名呢?iterator_category程序员已经明确声明了另一个类别,但默默地生成一个值是否是一个好主意,并且为iterator_category它生成一个与看起来完全不同的值concept也很奇怪。考虑这个不切实际的例子:#include <iostream>
#include <iterator>
// With the == operator, this is an input iterator, but nothing else.
struct WeirdIterator {
// Not an output iterator because …Run Code Online (Sandbox Code Playgroud) 我有一些简单的代码
#include<iterator>
int main() {
int y[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
auto a = std::begin(y);
std::cout << *a << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
1按预期打印出来。
但是如果我这样做:
void checkNested(int val [10]) {
auto a = std::begin(val);
std::cout << *a << std::endl;
}
int main() {
int y[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
checkNested(y);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
clang++我从和得到编译失败g++。具体来说clang++我得到:
auto a = std::begin(input);
^~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/initializer_list:89:5: …Run Code Online (Sandbox Code Playgroud) 我在这里遇到了一个问题,我以为我可以在互联网上找到一个简单的答案,但已经过了 1 小时了,我无法解决它。看起来很简单,但我找不到方法......
我有2节课:
#include <iostream>
#include <list>
using namespace std;
class classB;
class classA{
private :
string name;
list<classB*> listClassB;
public:
void getListClassB() const;
};
class classB{
private:
string name;
list<classA*> listClassA;
public:
void getListClassA() const;
};
Run Code Online (Sandbox Code Playgroud)
我对该getListClassB()方法所做的是:
void classA::getListClassB() const {
for(list<classB*>::iterator it = listClassB.begin(); it != listClassB.end; it++){
//Stuff
}
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio Code 告诉我有一个错误listClassB来自list<classB*>::iterator it = listClassB.begin()
完整的错误是:
there is no appropriate user-defined conversion of
"std::_List_const_iterator<std::_List_val<std::conditional_t<true, std::_List_simple_types<classB *>, std::_List_iter_types<classB *, size_t, …Run Code Online (Sandbox Code Playgroud) 我有一个向量
std::vector<Object*> objects;
Run Code Online (Sandbox Code Playgroud)
如果找到对象,则删除该对象的方法:
void Remove(Object *o)
{
objects.erase(
std::remove_if(
objects.begin(), objects.end(),
[&o](Object *_object) {
if (o == _object)
{
delete _object;
return true;
}
return false;
}
),
objects.end()
);
}
Run Code Online (Sandbox Code Playgroud)
这安全吗?我不应该打电话吗delete?但后来会erase打电话delete给我吗?我有点困惑。这会使迭代器无效或泄漏内存吗?