A generator is a special routine that can be used to control the iteration behaviour of a loop
以C#為程式語言示範,假設沒有控制Iterator的話,印出一到一百間所有質數,我們會這麼寫。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
static IList<int> GeneratorPrimes() { var result = new List<int>(); for (int i = 2; i <= 100; i++) { bool flag = true; for (int j = 2; j * j <= i && flag; j++) if (i % j == 0) flag = false; if (flag) result.Add(i); } return result; } IList<int> ans = GeneratorPrimes(); foreach (var item in ans) { Console.WriteLine(" {0} ", item); }
public class PrimesGenerator : IEnumerator<int> { int current, next; public PrimesGenerator() { Reset(); } private void calcNext() { for (next++; ; next++) { bool flag = true; for (int i = 2; flag && i * i <= next; i++) if (next % i == 0) flag = false; if (flag) break; } } public bool MoveNext() { return current < 100; } public void Dispose() { } public int Current { get { int ret = current; current = next; calcNext(); return ret; } } object System.Collections.IEnumerator.Current { get { int ret = current; current = next; calcNext(); return ret; } } public void Reset() { current = 2; next = 3; } } public class IEnumerablePrimes : IEnumerable<int> { public IEnumerator<int> GetEnumerator() { return new PrimesGenerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static IEnumerable<int> GeneratorPrime() { return new IEnumerablePrimes(); }
public static IEnumerable<int> GeneratorPrime() { for (int i = 2; i <= 100; i++) { bool flag = true; for (int j = 2; j * j <= i && flag; j++) if (i % j == 0) flag = false; if (flag) yield return i; } }
int bar; void foo() {} class Foo { static int value; void Bar(int); }; int Foo::value = 0; void Foo::Bar(int) {}
Linux
在Linux底下可以用nm來指令
1
$ nm -gC test.so
g 列出所有External symbols
c 由於C++支援Function overload,要區別同名的函數名稱的話,需要在後方加上一些符號以供區別,而Demangle就是讓這些奇形怪狀的符號變成人可以看懂得版本。 以上的結果如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14
000000000020102c B bar 0000000000201028 B __bss_start w __cxa_finalize@@GLIBC_2.2.5 0000000000201028 D _edata 0000000000201038 B _end 00000000000006e4 T _fini w __gmon_start__ 00000000000005a0 T _init w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable w _Jv_RegisterClasses 00000000000006d0 T foo() 00000000000006d6 T Foo::Bar(int) 0000000000201030 B Foo::value
#include <stdio.h> int main() { long long s = 0; long long count; scanf("%lld", &count); for (long long i = 1; i <= count; i++) s += i; printf("%llu\n", s); return 0; }
class Base { } class Derived : Base { } public static void Run(IEnumerable<Base> bases) { } IEnumerable<Derived> derivedBases = new Derived[] { new Derived(), new Derived() }; Run(derivedBases);
類似的程式碼在C++就失敗了…
Covariance Example lang: c#
1 2 3 4 5 6 7 8 9 10 11 12
class Animal { public void Feed() {} } class Frog : Animal { } static void DoSomethingToAFrog(Action<Frog> action, Frog frog) { action(frog); } Action<Animal> feed = animal => { animal.Feed(); }; DoSomethingToAFrog(feed, new Frog());