C++ string 用法详解

字符串分割(C++) 

C++ QUICK REFERENCE

Matt Mahoney, mmahoney@cs.fit.edu

DECLARATIONS
enum weekend {SAT,SUN};   // weekend is a type with values SAT and SUN
enum weekend day;         // day is a variable of type weekend
enum weekend {SAT=0,SUN=1};  // Explicit representation as int
enum {SAT,SUN} day;       // Anonymous enum

STATEMENTS

switch (x) {              // x must be int
  case X1: a;             // If x == X1 (must be a const), jump here
  case X2: b;             // Else if x == X2, jump here
  default: c;             // Else jump here (optional)
}
try { a; }
catch (T t) { b; }        // If a throws a T, then jump here
catch (...) { c; }        // If a throws something else, jump here

FUNCTIONS

T operator+(T x, T y);    // a+b (if type T) calls operator+(a, b)
T operator-(T x);         // -a calls function operator-(a)
T operator++(int);        // postfix ++ or -- (parameter ignored)
extern "C" {void f();}    // f() was compiled in C
Function parameters and return values may be of any type. A function must either be declared or defined before it is used. It may be declared first and defined later. Every program consists of a set of a set of global variable declarations and a set of function definitions (possibly in separate files), one of which must be:

 

EXPRESSIONS
Operators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. All others are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run time checks for arrays out of bounds, invalid pointers, etc.
::X                       // Global name X

typeid(x)                 // Type of x

dynamic_cast<T>(x)        // Converts x to a T, checked at run time
static_cast<T>(x)         // Converts x to a T, not checked
reinterpret_cast<T>(x)    // Interpret bits of x as a T
const_cast<T>(x)          // Converts x to same type T but not const

new T                     // Address of newly allocated T object
new T[x]                  // Address of allocated n-element array of T
delete p                  // Destroy and free object at address p
delete[] p                // Destroy and free array of objects at p

CLASSES

class T {                 // A new type
private:                  // Section accessible only to T's member functions
protected:                // Also accessable to classes derived from T
public:                   // Accessable to all
  int x;                  // Member data
  void f();               // Member function
  void g() {return;}      // Inline member function
  void h() const;         // Does not modify any data members
  int operator+(int y);   // t+y means t.operator+(y)
  int operator-();        // -t means t.operator-()
  T(): x(1) {}            // Constructor with initialization list
  T(const T& t): x(t.x) {}  // Copy constructor
  T& operator=(const T& t) {x=t.x; return *this; }  // Assignment operator
  ~T();                   // Destructor (automatic cleanup routine)
  explicit T(int a);      // Allow t=T(3) but not t=3
  operator int() const {return x;}  // Allows int(t)
  friend void i();        // Global function i() has private access
  friend class U;         // Members of class U have private access
  static int y;           // Data shared by all T objects
  static void l();        // Shared code.  May access y but not x
  class Z {};             // Nested class T::Z
  typedef int V;          // T::V means int
};
void T::f() {             // Code for member function f of class T
  this->x = x;}           // this is address of self (means x=x;)
int T::y = 2;             // Initialization of static member (required)
T::l();                   // Call to static member
struct T {                // Equivalent to: class T { public:
  virtual void f();       // May be overridden at run time by derived class
  virtual void g()=0; };  // Must be overridden (pure virtual)
class U: public T {};     // Derived class U inherits all members of base T
class V: private T {};    // Inherited members of T become private
class W: public T, public U {};  // Multiple inheritance
class X: public virtual T {}; // Classes derived from X have base T directly
All classes have a default copy constructor, assignment operator, and destructor, which perform the corresponding operations on each data member and each base class as shown above. There is also a default no-argument constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and destructors do not inherit.

 

TEMPLATES

template <class T> T f(T t);        // Overload f for all types
template <class T> class X {        // Class with type parameter T
  X(T t); };                        // A constructor
template <class T> X<T>::X(T t) {}  // Definition of constructor
X<int> x(3);                        // An object of type "X of int"
template <class T, class U=T, int n=0>  // Template with default parameters

NAMESPACES
namespace N {class T {};} // Hide name T
N::T t;                   // Use name T in namespace N
using namespace N;        // Make T visible without N::

C/C++ STANDARD LIBRARY

Only the most commonly used functions are listed. Header files without .h are in namespace std. File names are actually lower case.
STDIO.H, CSTDIO (Input/output)

FILE* f=fopen("filename", "r");  // Open for reading, NULL (0) if error
  // Mode may also be "w" (write) "a" append, "a+" update, "rb" binary
fclose(f);                // Close file f
fprintf(f, "x=%d", 3);    // Print "x=3"  Other conversions:
  "%5d %u %-8ld"            // int width 5, unsigned int, long left just.
  "%o %x %X %lx"            // octal, hex, HEX, long hex
  "%f %5.1f"                // float or double: 123.000000, 123.0
  "%e %g"                   // 1.23e2, use either f or g
  "%c %s"                   // char, char*
  "%%"                      // %
sprintf(s, "x=%d", 3);    // Print to array of char s
printf("x=%d�, 3);        // Print to stdout (screen unless redirected)
fprintf(stderr, ...       // Print to standard error (not redirected)
getc(f);                  // Read one char (as an int) or EOF from f
ungetc(c, f);             // Put back one c to f
getchar();                // getc(stdin);
putc(c, f)                // fprintf(f, "%c", c);
putchar(c);               // putc(c, stdout);
fgets(s, n, f);           // Read line into char s[n] from f.  NULL if EOF
gets(s)                   // fgets(s, INT_MAX, f); no bounds check
fread(s, n, 1, f);        // Read n bytes from f to s, return number read
fwrite(s, n, 1, f);       // Write n bytes of s to f, return number written
fflush(f);                // Force buffered writes to f
fseek(f, n, SEEK_SET);    // Position binary file f at n
ftell(f);                 // Position in f, -1L if error
rewind(f);                // fseek(f, 0L, SEEK_SET); clearerr(f);
feof(f);                  // Is f at end of file?
ferror(f);                // Error in f?
perror(s);                // Print char* s and error message
clearerr(f);              // Clear error code for f
remove("filename");       // Delete file, return 0 if OK
rename("old", "new");     // Rename file, return 0 if OK
f = tmpfile();            // Create temporary file in mode "wb+"
tmpnam(s);                // Put a unique file name in char s[L_tmpnam]
STDLIB.H, CSTDLIB (Misc. functions)

atof(s); atol(s); atoi(s);// Convert char* s to float, long, int
rand(), srand(seed);      // Random int 0 to RAND_MAX, reset rand()
void* p = malloc(n);      // Allocate n bytes.  Obsolete: use new
free(p);                  // Free memory.  Obsolete: use delete
exit(n);                  // Kill program, return status n
system(s);                // Execute OS command s (system dependent)
getenv("PATH");           // Environment variable or 0 (system dependent)
abs(n); labs(ln);         // Absolute value as int, long
STRING.H, CSTRING (Character array handling functions)

Strings are type char[] with a '\0' in the last element used.
strcpy(dst, src);         // Copy string. Not bounds checked
strcat(dst, src);         // Concatenate to dst. Not bounds checked
strcmp(s1, s2);           // Compare, <0 if s1<s2, 0 if s1==s2, >0 if s1>s2
strncpy(dst, src, n);     // Copy up to n chars, also strncat(), strncmp()
strlen(s);                // Length of s not counting \0
strchr(s,c); strrchr(s,c);// Address of first/last char c in s or 0
strstr(s, sub);           // Address of first substring in s or 0
  // mem... functions are for any pointer types (void*), length n bytes
memmove(dst, src, n);     // Copy n bytes from src to dst
memcmp(s1, s2, n);        // Compare n bytes as in strcmp
memchr(s, c, n);          // Find first byte c in s, return address or 0
memset(s, c, n);          // Set n bytes of s to c
CTYPE.H, CCTYPE (Character types)

isalnum(c);               // Is c a letter or digit?
isalpha(c); isdigit(c);   // Is c a letter?  Digit?
islower(c); isupper(c);   // Is c lower case?  Upper case?
tolower(c); toupper(c);   // Convert c to lower/upper case
MATH.H, CMATH (Floating point math)

sin(x); cos(x); tan(x);   // Trig functions, x (double) is in radians
asin(x); acos(x); atan(x);// Inverses
atan2(y, x);              // atan(y/x)
sinh(x); cosh(x); tanh(x);// Hyperbolic
exp(x); log(x); log10(x); // e to the x, log base e, log base 10
pow(x, y); sqrt(x);       // x to the y, square root
ceil(x); floor(x);        // Round up or down (as a double)
fabs(x); fmod(x, y);      // Absolute value, x mod y
TIME.H, CTIME (Clock)

clock()/CLOCKS_PER_SEC;   // Time in seconds since program started
time_t t=time(0);         // Absolute time in seconds or -1 if unknown
tm* p=gmtime(&t);         // 0 if UCT unavailable, else p->tm_X where X is:
  sec, min, hour, mday, mon (0-11), year (-1900), wday, yday, isdst
asctime(p);               // "Day Mon dd hh:mm:ss yyyy\n"
asctime(localtime(&t));   // Same format, local time
ASSERT.H, CASSERT (Debugging aid)

assert(e);                // If e is false, print message and abort
#define NDEBUG            // (before #include <assert.h>), turn off assert
NEW.H, NEW (Out of memory handler)

set_new_handler(handler); // Change behavior when out of memory
void handler(void) {throw bad_alloc();}  // Default
IOSTREAM.H, IOSTREAM (Replaces stdio.h)

cin >> x >> y;              // Read words x and y (any type) from stdin
cout << "x=" << 3 << endl;  // Write line to stdout
cerr << x << y << flush;    // Write to stderr and flush
c = cin.get();              // c = getchar();
cin.get(c);                 // Read char
cin.getline(s, n, '\n');    // Read line into char s[n] to '\n' (default)
if (cin)                    // Good state (not EOF)?
                            // To read/write any type T:
istream& operator>>(istream& i, T& x) {i >> ...; x=...; return i;}
ostream& operator<<(ostream& o, const T& x) {return o << ...;}
FSTREAM.H, FSTREAM (File I/O works like cin, cout as above)

ifstream f1("filename");  // Open text file for reading
if (f1)                   // Test if open and input available
  f1 >> x;                // Read object from file
f1.get(s);                // Read char or line
f1.getline(s, n);         // Read line into string s[n]
ofstream f2("filename");  // Open file for writing
if (f2) f2 << x;          // Write to file
IOMANIP.H, IOMANIP (Output formatting)

cout << setw(6) << setprecision(2) << setfill('0') << 3.1; // print "003.10"
STRING (Variable sized character array)

string s1, s2="hello";    // Create strings
s1.size(), s2.size();     // Number of characters: 0, 5
s1 += s2 + ' ' + "world"; // Concatenation
s1 == "hello world"       // Comparison, also <, >, !=, etc.
s1[0];                    // 'h'
s1.substr(m, n);          // Substring of size n starting at s1[m]
s1.c_str();               // Convert to const char*
getline(cin, s);          // Read line ending in '\n'
VECTOR (Variable sized array/stack with built in memory allocation)

vector<int> a(10);        // a[0]..a[9] are int (default size is 0)
a.size();                 // Number of elements (10)
a.push_back(3);           // Increase size to 11, a[10]=3
a.back()=4;               // a[10]=4;
a.pop_back();             // Decrease size by 1
a.front();                // a[0];
a[20]=1;                  // Crash: not bounds checked
a.at(20)=1;               // Like a[20] but throws out_of_range()
for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p)
  *p=0;                   // Set all elements of a to 0
vector<int> b(a.begin(), a.end());  // b is copy of a
vector<T> c(n, x);        // c[0]..c[n-1] init to x
T d[10]; vector<T> e(d, d+10);      // e is initialized from d
DEQUE (array/stack/queue)

deque<T> is like vector<T>, but also supports:
a.push_front(x);          // Puts x at a[0], shifts elements toward back
a.pop_front();            // Removes a[0], shifts toward front
UTILITY (Pair)

pair<string, int> a("hello", 3);  // A 2-element struct
a.first;                  // "hello"
a.second;                 // 3
MAP (associative array)

map<string, int> a;       // Map from string to int
a["hello"]=3;             // Add or replace element a["hello"]
for (map<string, int>::iterator p=a.begin(); p!=a.end(); ++p)
  cout << (*p).first << (*p).second;  // Prints hello, 3
a.size();                 // 1
ALGORITHM (A collection of 60 algorithms on sequences with iterators)

min(x, y); max(x, y);     // Smaller/larger of x, y (any type defining <)
swap(x, y);               // Exchange values of variables x and y
sort(a, a+n);             // Sort array a[0]..a[n-1] by <
sort(a.begin(), a.end()); // Sort vector or deque

C++ QUICK REFERENCE的更多相关文章

  1. Quick Reference Card Urls For Web Developer

    C# C# Cheatsheet & Notes Coding Guidelines for C# 3.0, 4.0, 5.0 Core C# and .NET Quick Reference ...

  2. ASP.NET Web Pages (Razor) API Quick Reference

    ASP.NET Web Pages (Razor) API Quick Reference By Tom FitzMacken|February 10, 2014 Print This page co ...

  3. MongoDB - The mongo Shell, mongo Shell Quick Reference

    mongo Shell Command History You can retrieve previous commands issued in the mongo shell with the up ...

  4. The Pragmatic Programmer Quick Reference Guide

    1.关心你的技艺 Care About Your Craft 如果不在乎能否漂亮地开发出软件,你又为何要耗费生命去开发软件呢? 2.思考!你的工作 Think! About Your Work 关掉自 ...

  5. [译]AMQP 0-9-1 Quick Reference : basic

    Basic basic.ack(delivery-tag delivery-tag, bit multiple)Support: fullAcknowledge one or more message ...

  6. SQL Quick Reference From W3Schools

    SQL Statement Syntax AND / OR SELECT column_name(s)FROM table_nameWHERE conditionAND|OR condition AL ...

  7. eigen quick reference

    参考: http://eigen.tuxfamily.org/dox/AsciiQuickReference.txt // A simple quickref for Eigen. Add anyth ...

  8. objective-c Quick Reference

  9. GPDB 5.x PSQL Quick Reference

    General \copyright show PostgreSQL usage and distribution terms \g [FILE] or ; execute query (and se ...

随机推荐

  1. Oracle11g中ORA-01790

    问题源于群里有人问如何让查询的结果值+1,方法其实很简单,直接在SQL语句中+1就可以,如果有空可以用NVL处理. 但是测试的时候我使用了UNION ALL(测试的字段是varchar2类型),结果报 ...

  2. Git 提交大文件提示 fatal: The remote end hung up unexpectedly

    使用gitlab搭建的git server,如果直接使用http的方式去提交的话,提交小文件不会有问题,但是提交大文件时,会出错: fatal: The remote end hung up unex ...

  3. linux 命令大全(转)

    系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...

  4. qml操作播放器

    现在增加了一个filter属性,所以可以很好和opencv结合.转一篇文章(http://blog.qt.io/blog/2015/03/20/introducing-video-filters-in ...

  5. 青蛙的烦恼(dp好题)

    有n片荷叶正好在一凸多边形顶点上 有一只小青蛙恰好站在1号荷叶的点 小青蛙可以从一片荷叶上跳到另外任意一片荷叶上 给出N个点的坐标N<800 求小青蛙想通过最短的路程遍历所有的荷叶一次且仅一次的 ...

  6. C# 子窗体点击按钮产生的新子窗体放在父窗体里

    情景展示: 父窗体Form1,左边是按钮,右边是panel(放置子窗体) 父窗体点击按钮,在panel显示第一个子窗体AA, AA有个按钮,点击按钮,是第二个子窗体ZZ, 怎样将AA的子窗体ZZ也显示 ...

  7. Redis系列-存储篇hash主要操作函数小结

    阳光透过玻璃,洒在身上,一杯暖茶在手,说不尽的安逸自得,让我有种想再写篇blog的冲动.上篇主要谈了string,这里谈谈hash吧!hash是一些列key value(field value)的映射 ...

  8. 7 libjpeg使用

    一.交叉编译libjepg编译 tar xzf libjpeg-turbo-1.2.1.tar.gz ./configure –help ./configure --prefix=/work/proj ...

  9. Hibernate中的集合映射

    1.定义实体 public class User { private int userId; private String userName; private Set<String> ad ...

  10. javaNIO是什么?由那几部分组成?各部分的作用。

    Java NIO 由以下几个核心部分组成: Channels Buffers Selectors 虽然Java NIO 中除此之外还有很多类和组件,但在我看来,Channel,Buffer 和 Sel ...