分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net
primitive types | arithmetic and logic | strings | regexes | dates and time | arrays | dictionaries | functions
execution control | files | directories | processes
and environment | libraries and namespaces | objects | generic types
reflection | web | contact
c++ (1983) | objective c (1986) | java (1995) | c# (2001) | |
---|---|---|---|---|
hello word |
$ cat hello.cpp #include <iostream> using namespace std; int main(int argc, char**arg) { cout << "Hello, World!" << endl; } $ g++ hello.cpp $ ./a.out Hello, World! |
$ cat hello.m #include <stdio.h> int main(int argc, char **argv) { printf("Hello, World!\n"); } $ gcc hello.m $ ./a.out Hello, World! |
$ cat Hello.java public class Hello { public static void main(String[] args) { System.out.println("Hello, World!"); } } $ javac Hello.java $ java Hello Hello, World! |
$ cat hello.cs using System; public class Hello { public static void Main() { Console.WriteLine("Hello, World!"); } } $ mcs hello.cs $ mono hello.exe Hello, World! |
version used |
g++ 4.2 | gcc 4.2 | java 1.6 | mono 2.10 (C# 4.0) |
version |
$ g++ —version | $ gcc —version | $ javac -version | $ mcs —version |
libraries used |
STL and Boost | Foundation Framework | Java API | Base Class Library |
source, header, object file suffix | .cpp .hpp .o | .m .h .o | .java none .class | .cs none .exe or.dll |
null |
NULL | NULL | null | null |
printf |
cout << "count: " << 7 << endl; | printf("count: %d\n", 7); | System.out.printf("count: %d", 7); | System.Console.WriteLine("count: {0}", 7); |
case and underscores in names |
A_MACRO_NAME AClassName AMethodName() or a_method_name() a_variable_name |
A_MACRO_NAME AClassName [obj aMsgName:arg aLabelName:arg] aVariableName |
AClassName aMethodName() aVariableName |
AClassName AMethodName() aVariableName |
coalesce |
string s1 = s2 || "was null"; | NSString *s1 = s2 || @"was null"; | String s1 = s2 == null ? "was null" : s2; | string s1 = s2 ?? "was null"; |
primitive types | ||||
c++ | objective c | java | c# | |
declare primitive type on stack |
int i; int j = 3; int k(7); |
int i; int j = 3; |
int i; int j = 3; |
int i; int j = 3; |
allocate primitive type on heap | int *ip = new int; |
#include <stdlib.h>
int *ip = malloc(sizeof(int)); |
primitive types are always stack allocated. Use a wrapper class to store on the heap: Integer i = new Integer(0); |
object i = 0; |
free primitive type on heap | delete i; |
#include <stdlib.h>
free(ip); |
garbage collected | garbage collected |
value of uninitialized primitive types | same as C. However, C++ provides a no-argument constructor for each primitive type which zero-initializes it. | stack variables and heap variables allocated with malloc have indeterminate values. Global and static variables and heap variables allocated with calloc are zero-initialized. | zero-initialized | compiler prevents use of uninitialized variables in some circumstances, and zero-initializes in others |
boolean types |
bool | BOOL | boolean | bool |
signed integer types |
signed char 1+ byte short int 2+ bytes int 2+ bytes long int 4+ bytes long long int 4+ bytes |
signed char 1+ byte short int 2+ bytes int 2+ bytes long int 4+ bytes long long int 4+ bytes |
byte 1 byte short 2 bytes int 4 bytes long 8 bytes |
sbyte 1 byte short 2 bytes int 4 bytes long 8 bytes |
unsigned integer types |
unsigned char: 8+ unsigned short int 2 bytes+ unsigned int 2 bytes+ unsigned long int 4+ bytes unsigned long long int 4+ bytes |
unsigned char: 8+ unsigned short int 2 bytes+ unsigned int 2 bytes+ unsigned long int 4+ bytes unsigned long long int 4+ bytes |
char 2 bytes |
byte 1 byte ushort 2 bytes uint 4 bytes ulong 8 bytes |
floating point and decimal types |
float double long double |
float double long double |
float 4 bytes double 8 bytes |
float 4 bytes double 8 bytes decimal 12 bytes |
typedef |
typedef int customer_id; customer_id cid = 3; |
typedef int customer_id; customer_id cid = 3; |
none | none |
enum |
enum day_of_week { mon, tue, wed, thu, fri, sat, sun }; day_of_week d = tue; |
enum day_of_week { mon, tue, wed, thu, fri, sat, sun }; enum day_of_week d = tue; |
public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN }; DayOfWeek d = DayOfWeek.TUE; |
public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN }; DayOfWeek d = DayOfWeek.TUE; |
arithmetic and logic | ||||
c++ | objective c | java | c# | |
true and false |
true false | YES NO | true false | true false |
falsehoods |
false 0 0.0 NULL | 0 0.0 NULL | false | false |
logical operators |
&& || ! and or not |
&& || ! | && || ! | && || ! |
relational operators | == != < > <= >= | == != < > <= >= | == != < > <= >= | == != < > <= >= |
arithmetic operators |
+ - * / % | + - * / % | + - * / % | + - * / % |
division by zero | process sent a SIGFPE signal | process sent a SIGFPE signal | throws java.lang.ArithmeticException | throws System.DivideByZeroException |
power |
#include <boost/math/special_functions.hpp> boost::math::powm1<double>(2.0,3.0)+1 |
#include <math.h>
pow(2.0,3.0); |
Math.pow(2.0,3.0); | System.Math.Pow(2.0,3.0); |
absolute value |
#include <stdlib.h>
int i = -7; |
#include <stdlib.h>
int i = -7; |
Math.abs(-7) Math.abs(-7.77) |
System.Math.Abs(-7) System.Math.Abs(-7.77) |
transcendental functions |
#include <math.h>
sqrt exp log log2 log10 sin cos tan asin acos atan atan2 |
#include <math.h>
sqrt exp log log2 log10 sin cos tan asin acos atan atan2 |
Math.sqrt Math.exp Math.log none Math.log10 Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2 |
using System; Math.Sqrt Math.Exp Math.Log none Math.Log10 Math.Sin Math.Cos Math.Tan Math.Asin Math.Acos Math.Atan Math.Atan2 |
arithmetic truncation |
#include <math.h> double d = 3.77; long trunc = (long)d; long rnd = round(d); long flr = floorl(d); long cl = ceill(d); |
#include <math.h> double d = 3.77; long trunc = (long)d; long rnd = round(d); long flr = floorl(d); long cl = ceill(d); |
(long)3.77 Math.round(3.77) (long)Math.floor(3.77) (long)Math.ceil(3.77) |
using System; (long)3.77 Math.Round(3.77) Math.Floor(3.77) Math.Ceiling(3.77) |
random integer |
#include <boost/random.hpp> using namespace boost; mt19937 rng; uniform_int<> ui(0,RAND_MAX); variate_generator<mt19937&, uniform_int<> > brand(rng, ui); int i = brand() |
#include <stdlib.h>
int i = rand(); |
java.util.Random r = new java.util.Random(); int i = r.nextInt(); |
System.Random r = new System.Random(); int i = r.Next(); |
bit operators |
<< >> & | ^ ~ bitand bitor comp |
<< >> & | ^ ~ | << >> & | ^ ~ | << >> & | ^ ~ |
strings | ||||
c++ | objective c | java | c# | |
type |
std::string | NSString | java.lang.String | string |
literal |
none | @"hello" | "don‘t say\"no\"" | "hello" |
newline in literal? | string literals can extend over multiple lines, but the newlines do not appear in the resulting string | string literals can extend over multiple lines, but the newlines do not appear in the resulting string | no | string literals can extend over multiple lines, but the newlines do not appear in the resulting string |
escapes |
\a \b \f \n \r \t \v \xhh \\ \" \‘ \o \oo \ooo | \a \b \f \n \r \t \v \xhh \\ \" \‘ \o \oo \ooo | \b \f \n \r \t \uhhhh \\ \" \‘ \o \oo \ooo | \a \b \f \n \r \t \v \xhh \xhhhh \\ \" \‘ \o \oo \ooo |
allocate string | string *s = new string("hello"); | NSString *s = @"hello"; |
String s = "hello"; String t = new String(s); |
string s = "hello"; string t = string.Copy(s); |
length |
s->length() | [s length] | s.length() | s.Length |
comparison |
string *s1 = new string("hello"); string *s2 = new stringt("world"); cout << s1->compare(*s2) << endl; |
[@"hello" compare:@"hello"] | "hello".compareTo("world") | "hello".CompareTo("world") |
semantics of == | value comparison | object identity comparison | object identity comparison | value comparison |
to C string |
s->c_str() | [s UTF8String] | none | none |
string to number |
#include <sstream> stringstream ss("7 14.3 12"); int i; double d; long l; ss >> i >> d >> l; |
[@"14" integerValue] [@"14" longLongvalue] [@"14.7" floatValue] [@"14.7" doubleValue] |
Byte.parseByte("14") Short.parseShort("14") Integer.parseInt("14") Long.parseLong("14") Float.parseFloat("14.7") Double.parseDouble("14.7") |
byte.Parse("14") short.Parse("14") int.Parse("14") long.Parse("14") float.Parse("14") double.Parse("14") decimal.Parse("14") |
number to string |
Integer.toString(14) Long.toString(14) Double.toString(14.7) |
14.ToString() 14.7.ToString() |
||
split |
#include <boost/algorithm/string.hpp> #include <vector> string s("Bob Amy Ned"); vector<string> vec; boost::split(vec, s, boost::is_any_of(" ")); |
[@"Bob Ned Amy" componentsSeparatedByString:@" "] | "Bob Ned Amy".split(" ") | string[] names = "Bob Ned Amy".Split(‘ ‘); |
join |
System.String.Join(", ", names) | |||
concatenate |
string *s1 = new string("hello"); string *s2 = new string(" world"); cout << *s1 + *s2 << endl; |
NSString *s1 = @"hello"; NSString *s2 = @" world"; NSString *s3 = [s1 stringByAppendingString:s2]; |
"hello" + " world" | "hello" + " world" |
substring | string("hello").substr(2,2) | [@"hello" substringWithRange:NSMakeRange(2,2)] | "hello".substring(2,4) | "hello".Substring(2,2) |
index |
string("hello").find("ll") | [@"hello" rangeOfString:@"ll"].location | "hello".indexOf("ll") | "hello".IndexOf("ll") |
sprintf |
#include <sstream> ostringstream o(‘‘); o << "Spain" << ": " << 7; o.str(); |
[NSString stringWithFormat:@"%@: %d", @"Spain", 7] | String.format("%s: %d", "Spain", 7) | string.Format("{0}: {1}", "Spain", 7) |
uppercase |
#include <boost/algorithm/string.hpp> string s("hello"); boost::to_upper(s); |
[@"hello" uppercaseString] | "hello".toUpperCase() | "hello".ToUpper() |
lowercase |
#include <boost/algorithm/string.hpp> string s("HELLO"); boost::to_upper(s); |
[@"HELLO" lowercaseString] | "HELLO".toLowerCase() | "HELLO".ToLower() |
trim |
#include <boost/algorithm/string.hpp> string s(" hello "); boost::trim(s); |
[@" hello " stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] | " hello ".trim() | " hello ".Trim() |
pad on right | [@"hello" stringByPaddingToLength:10 withString:@" " startingAtIndex:0] | |||
regular expressions | ||||
c++ | objective c | java | c# | |
regex match |
#include <boost/xpressive/xpressive.hpp> using namespace boost::xpressive; sregex re = sregex::compile(".*ll.*"); smatch matches; string s("hello"); bool is_match = regex_match(s, matches, re); |
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @".*ll.*"]; BOOL is_match = [pred evaluateWithObject:@"hello"]; |
boolean isMatch = "hello".matches(".*ll.*"); |
using System.Text.RegularExpressions; Regex regex = new Regex("ll"); bool isMatch = regex.IsMatch("hello"); |
regex substitute |
#include <boost/xpressive/xpressive.hpp> using namespace boost::xpressive; string s("hello"); sregex re1 = as_xpr("ll"); string format1("LL"); string result1 = regex_replace(s, re1, format1, regex_constants::format_first_only); sregex re2 = as_xpr("l"); string format2("L"); string result2 = regex_replace(s, re2, format2); |
String s1 = "hello".replace("ll","LL"); String s2 = "hello".replaceAll("l","L"); |
using System.Text.RegularExpressions; Regex r1 = new Regex("ll"); String s1 = r1.Replace("hello", "LL", 1); Regex r2 = new Regex("l"); String s2 = r2.Replace("hello", "L"); |
|
dates and time | ||||
c++ | objective c | java | c# | |
date/time type |
java.util.Date | System.DateTime | ||
current date/time |
long millis = System.currentTimeMillis(); Date dt = new Date(millis); |
DateTime dt = DateTime.Now(); | ||
to unix epoch, from unix epoch |
long epoch = dt.getTimeInMillis()/1000;
Date dt2 = new Date(epoch * 1000); |
long hundredM = 100*1000*1000; long sec = dt.ToFileTimeUtc() / hundredM; long epoch = sec - 1164444480; long ft = (epoch + 1164444480) * hundredM; |
||
strftime |
String s = "yyyy-MM-dd HH:mm:ss"; DateFormat fmt = new SimpleDateFormat(s); String s2 = fmt.format(dt); |
String s = "yyyy-MM-dd HH:mm:ss"); String s2 = dt.ToString(s); |
||
strptime |
String s = "2011-05-03 17:00:00"; Date dt2 = fmt.parse(s); |
CultureInfo enUS = new CultureInfo("en-US"); DateTime dt2 = DateTime.ParseExact( |
||
arrays | ||||
c++ | objective c | java | c# | |
allocate array on stack | int a[10]; | int a[10]; | arrays must be allocated on heap | arrays must be allocated on heap |
allocate array on heap | int *a = new int[10]; |
#include <stdlib.h> int *a = calloc(10, sizeof(int)); |
int[] a = new int[10]; | int[] a = new int[10]; |
free array on heap | delete[] a; |
#include <stdlib.h> free(a); |
garbage collected | garbage collected |
array literal | int a[] = {1,2,3}; | NSArray *a = [NSArray arrayWithObjects:@"hello", @"goodbye", nil]; | int[] a = {1,2,3}; | int[] a = {1,2,3}; |
array access |
a[0] | [a objectAtIndex:0] | a[0] | a[0] |
length |
none | [a count] | a.length | a.Length |
array out-of-bounds result | undefined, possible SIGSEGV | raises NSRangeException exception | ArrayIndexOutOfBoundsException | IndexOutOfRangeException |
array iteration |
int a[10]; for (i=0; i<10; i++ ) { do something with a[i] } |
NSEnumerator *i = [a objectEnumerator]; id o; while (o = [i nextObject]) { do something with o } |
for (String name : names) { | foreach (string name in names) { |
struct definition |
class MedalCount { public: const char *country; int gold; int silver; int bronze; }; |
struct medal_count { const char* country; int gold; int silver; int bronze; }; |
public class MedalCount { public String country; public int gold; public int silver; public int bronze; } |
public class MedalCount { public string country; public int gold; public int silver; public int bronze; } |
struct declaration | MedalCount spain; | struct medal_count spain; | MedalCount spain = new MedalCount(); | MedalCount spain = new MedalCount(); |
struct initialization | MedalCount spain = { "Spain", 3, 7, 4 }; |
struct medal_count spain = { "Spain", 3, 7, 4}; struct medal_count france = { .gold = 8, .silver = 7, .bronze = 9, .country = "France" }; |
no object literal syntax; define a constructor | no object literal syntax; define a constructor |
struct member assignment |
spain.country = "Spain"; spain.gold = 3; spain.silver = 7; spain.bronze = 4; |
spain.country = "Spain"; spain.gold = 3; spain.silver = 7; spain.bronze = 4; |
spain.country = "Spain"; spain.gold = 3; spain.silver = 7; spain.bronze = 4; |
spain.country = "Spain"; spain.gold = 3; spain.silver = 7; spain.bronze = 4; |
struct member access | int spain_total = spain.gold + spain.silver + spain.bronze; | int spain_total = spain.gold + spain.silver + spain.bronze; | int spain_total = spain.gold + spain.silver + spain.bronze; | int spain_total = spain.gold + spain.silver + spain.bronze; |
vector declaration |
#include <vector> vector <int> vec; |
NSMutableArray *a = [NSMutableArray arrayWithCapacity:10]; | java.util.Vector<String> vec = new java.util.Vector<String>(); |
using System.Collections.Generic; List<string> l = new List<string>(); |
vector push | vec.push_back(7); | [a addObject:@"hello"]; |
vec.add("hello"); or vec.add(vec.size(), "hello") |
l.Add("hello"); |
vector pop |
vec.pop_back(); | [a removeLastObject]; | vec.removeElementAt(vec.size()-1); | l.RemoveAt(l.Count - 1); |
vector size |
vec.size() | [a count] | vec.size() | l.Count |
vector access |
vec[0] vec.at(0) |
[a objectAtIndex:0] | vec.elementAt(0) | l[0] |
vector out of bounds result |
vec[] has undefined behavior vec.at() raises out_of_range |
raises NSRangeException | throws ArrayIndexOutOfBoundsException | throws System.ArgumentOutOfRangeException |
vector iteration |
int sum = 0; vector<int>::iterator vi; for (vi = vec.begin(); vi != vec.end(); vi++ ) { sum += *vi; } |
NSEnumerator *i = [a objectEnumerator]; id o; while (o = [i nextObject]) { do something with o } |
for ( String s : vec ) { do something with s } |
foreach ( string s in l ) { do something with s } |
dictionaries | ||||
c++ | objective c | java | c# | |
pair |
pair<int, float> p(7, 3.14); cout << p.first << ", " << p.second << endl; |
using System.Collections.Generic; KeyValuePair<string,int> pr = new KeyValuePair<string,int>("hello",5); System.Console.WriteLine("{0} {1}", pr.Key, pr.Value); |
||
map declaration |
#include <map> map<string, int> m; |
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:10]; | java.util.TreeMap<String, Integer> m = new java.util.TreeMap<String, Integer>(); |
using System.Collections.Generic; Dictionary<string, int> dict = new Dictionary<string, int>(); |
map access |
m["hello"] = 5; cout << m["hello"]) << endl; |
[dict setObject:@"5" forKey:@"hello"]; [dict objectForKey:@"hello"] |
m.put("hello", 5); m.get("hello") |
dict.Add("hello", 5); dict["hello"] |
map size |
m.size() | [dict count] | m.size() | dict.Count |
map remove element | m.erase(m.find("hello")); | [dict removeObjectForKey:@"hello"]; | m.remove("hello"); | dict.Remove("hello"); |
map element not found result | NULL | NULL | null |
throws KeyNotFoundException in System.Collections.Generic |
map iterate |
map<string,int>::iterator mi; for (mi = m.begin(); mi != m.end(); mi++) { printf("%s %d", mi->first, mi->second) } |
NSEnumerator *i = [dict keyEnumerator]; id key; while ((key = [i nextObject])) { do something with key } |
for ( java.util.Map.Entry<String, Integer> e : m.entrySet() ) { use e.getKey() or e.getValue() } |
foreach ( KeyValuePair<string,int> e in dict) { use e.Key and e.Value } |
functions | ||||
c++ | objective c | java | c# | |
pass by value |
void use_integer(int i) { function body } int i = 7; use_integer(i); |
void use_integer(int i) { function body } int i = 7; use_integer(i); |
primitive types are always passed by value | primitive types are always passed by value |
pass by address |
void use_iptr(int *i) { function body } int i = 7; use_iptr(&i); |
void use_iptr(int *i) { function body } int i = 7; use_iptr(&i); |
none | none |
pass by reference |
void use_iref(int& i) { printf("using iref: %d", i); } int i = 7; use_iref(i); |
none | objects and arrays are always passed by reference | objects and arrays are always passed by reference |
default argument value | float log(float exp, float base=10.0) { | none | use method overloading | use method overloading |
named parameters | none |
+(float)weight: (float) w height: (float) h { return (w * 703) / (h * h); } +(float)height: (float) h weight: (float) w { return [BMI weight: w height: h]; } [BMI weight:155 height:70]; [BMI height:70 weight:155]; |
none |
added in C# 4.0: static int BMI(int weight, int height) { return (weight * 703) / (height * height); } BMI(weight: 123, height: 64); BMI(height: 64, weight: 123); |
function overloading | yes | method overloading only | yes | yes |
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net |
原文地址:https://www.cnblogs.com/sjwudhwhhw/p/10509907.html