我想知道是否有时候在foreach循环中使用IEnumerator来迭代集合是否有利?例如,有没有时间使用以下代码示例中的任何一个而不是另一个?
IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator();
while(classesEnum.MoveNext())
Console.WriteLine(classesEnum.Current);
Run Code Online (Sandbox Code Playgroud)
代替
foreach (var class in myClasses)
Console.WriteLine(class);
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个实用程序类来遍历目录中的所有文件,包括子目录和子子目录中的文件.我试图使用发电机,因为发电机很酷; 但是,我遇到了麻烦.
def grab_files(directory):
for name in os.listdir(directory):
full_path = os.path.join(directory, name)
if os.path.isdir(full_path):
yield grab_files(full_path)
elif os.path.isfile(full_path):
yield full_path
else:
print('Unidentified name %s. It could be a symbolic link' % full_path)
Run Code Online (Sandbox Code Playgroud)
当生成器到达目录时,它只是产生新生成器的内存位置; 它没有给我目录的内容.
如果已经有一个简单的库函数来递归列出目录结构中的所有文件,请告诉我它.我不打算复制库函数.
我正在尝试实现一些STL样式的排序算法.std::sort看起来像这样的原型(来自cplusplus.com):
template <class RandomAccessIterator>
void sort ( RandomAccessIterator first, RandomAccessIterator last );
Run Code Online (Sandbox Code Playgroud)
该函数通常被称为这样(虽然容器类型可以变化):
std::vector<int> myVec;
// Populate myVec
std::sort(myVec.begin(), myVec.end());
Run Code Online (Sandbox Code Playgroud)
我复制了std::sort我自己的排序功能的原型.要遍历要排序的容器,我执行以下操作:
template <class RandomAccessIterator>
void mySort(RandomAccessIterator first, RandomAccessIterator last) {
RandomAccessIterator iter;
for (iter = first; iter != last; ++iter) {
// Do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
很容易.但是如果我想使用反向迭代器呢?这在从两端对容器进行分类的算法中是方便的,例如鸡尾酒排序.
有没有办法从作为参数传入的迭代器中获取反向迭代器?如果我事先知道容器类型,我可以这样做:
template <class RandomAccessIterator>
void mySort(RandomAccessIterator first, RandomAccessIterator last) {
std::vector<int>::reverse_iterator riter(last);
std::vector<int>::reverse_iterator rend(first);
for ( ; riter != rend; ++riter) {
// Do stuff …Run Code Online (Sandbox Code Playgroud) 在Python中,对于二进制文件,我可以这样写:
buf_size=1024*64 # this is an important size...
with open(file, "rb") as f:
while True:
data=f.read(buf_size)
if not data: break
# deal with the data....
Run Code Online (Sandbox Code Playgroud)
有了我想逐行阅读的文本文件,我可以这样写:
with open(file, "r") as file:
for line in file:
# deal with each line....
Run Code Online (Sandbox Code Playgroud)
这是简写:
with open(file, "r") as file:
for line in iter(file.readline, ""):
# deal with each line....
Run Code Online (Sandbox Code Playgroud)
这个成语记录在PEP 234中,但我找不到二进制文件的类似习惯用法.
我试过这个:
>>> with open('dups.txt','rb') as f:
... for chunk in iter(f.read,''):
... i+=1
>>> i
1 # 30 MB file, …Run Code Online (Sandbox Code Playgroud) 我想知道JavaScript是否具有增强的for循环语法,允许您迭代数组.例如,在Java中,您可以简单地执行以下操作:
String[] array = "hello there my friend".split(" ");
for (String s : array){
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
输出是:
hello
there
my
friend
Run Code Online (Sandbox Code Playgroud)
有没有办法在JavaScript中执行此操作?或者我必须使用array.length和使用标准的循环语法如下?
var array = "hello there my friend".split(" ");
for (i=0;i<array.length;i++){
document.write(array[i]);
}
Run Code Online (Sandbox Code Playgroud) 我有一个对象列表,我想找到第一个给定方法为某些输入值返回true的对象.这在Python中相对容易:
pattern = next(p for p in pattern_list if p.method(input))
Run Code Online (Sandbox Code Playgroud)
但是,在我的应用程序中,通常不存在这样p的p.method(input)情况,因此这将引发StopIteration异常.有没有一种惯用的方法来处理这个而不用编写try/catch块?
特别是,似乎用类似if pattern is not None条件的东西处理这种情况会更干净,所以我想知道是否有一种方法可以扩展我的定义,pattern以便None在迭代器为空时提供一个值 - 或者如果还有更多Pythonic方式处理整体问题!
我知道如果试图通过简单的循环从集合中删除循环,我会得到这个异常:java.util.ConcurrentModificationException.但我正在使用Iterator,它仍然会产生这个异常.知道为什么以及如何解决它?
HashSet<TableRecord> tableRecords = new HashSet<>();
...
for (Iterator<TableRecord> iterator = tableRecords.iterator(); iterator.hasNext(); ) {
TableRecord record = iterator.next();
if (record.getDependency() == null) {
for (Iterator<TableRecord> dependencyIt = tableRecords.iterator(); dependencyIt.hasNext(); ) {
TableRecord dependency = dependencyIt.next(); //Here is the line which throws this exception
if (dependency.getDependency() != null && dependency.getDependency().getId().equals(record.getId())) {
tableRecords.remove(record);
}
}
}
}
Run Code Online (Sandbox Code Playgroud) 我无法表达Iterator实现的返回值的生命周期.如何在不更改迭代器的返回值的情况下编译此代码?我希望它返回一个引用的向量.
很明显,我没有正确使用生命周期参数,但在尝试了我放弃的各种方法之后,我不知道如何处理它.
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 …Run Code Online (Sandbox Code Playgroud) 似乎std :: bitset没有STL迭代器.
因此,我不能做到以下几点:
std::bitset<8> bs;
for (auto it: bs) {
std::cout << "this can not be done out of the box\n";
}
Run Code Online (Sandbox Code Playgroud)
相反,我必须:
std::bitset<8> bs;
for (std::size_t i = 0; i < bs.size(); ++i) {
std::cout << bs[i] << '\n';
}
Run Code Online (Sandbox Code Playgroud)
没有迭代器,我也不能将bitset与任何STL算法一起使用.
为什么委员会决定从bitset中排除迭代器?
我想range在c ++中创建一个类似-的构造,它将像这样使用:
for (auto i: range(5,9))
cout << i << ' '; // prints 5 6 7 8
for (auto i: range(5.1,9.2))
cout << i << ' '; // prints 5.1 6.1 7.1 8.1 9.1
Run Code Online (Sandbox Code Playgroud)
处理整数情况相对容易:
template<typename T>
struct range
{
T from, to;
range(T from, T to) : from(from), to(to) {}
struct iterator
{
T current;
T operator*() { return current; }
iterator& operator++()
{
++current;
return *this;
}
bool operator==(const iterator& other) { return …Run Code Online (Sandbox Code Playgroud)