new
, delete
#include <string>
std::string myname = "sprout";
size_t len = myname.length();
sprout.insert(6, "zzz");// sprout == "sproutzzz"
size_t pos = myname.find("pro");
// 判斷是否找不到
pos == std::string::npos
#include <iomanip>
std::cout << std::hex << 123;
std::cout << std::fixed << std::setprecision(2) << 3.1415926;
#include <sstream>
std::stringstream ss;
ss << XXX;
ss >> OOO;
ss.clear();
int *a, *b;
int x = 123; // 取值 x, 取位址 &x
int *ptr; // ptr(的值)存位址,指向 int
ptr = &x;
*ptr = 456; // 取值 ptr, 取指向位址中的值 *ptr
int b[5] = {2, 3, 5, 7, 8};
*(b + 3); // == b[3]
int x = 123;
int &y = x;
y = 456;
void swap(int a, int b);
void swap(int *a, int *b);
void swap(int &a, int &b);
new
使用之後記得 delete
int n;
Student *stu = new Student[n];
delete[] stu;
SproutStudent sprout;
sprout.grade;
SproutStudent *sptr = &sprout;
sptr->grade;
bool isPass(const Student& rhs);
int totalGrade(const Student rhs[]);
vector
:伸縮自如的陣列list
:雙向鏈結串列stack
:類似疊東西,優先取得最後的資料queue
:類似排隊,優先取得最早的資料std::vector<int> vec;
std::vector<int>::iterator it;
it = vec.begin();
for (; it != vec.end(); ++it) {
std::cout << *it << std::endl;
}
insert
, erase
std::sort
排序#include <algorithm>
int arr[5];
std::sort(arr, arr + 5);
vector<int> vec;
std::sort(vec.begin(), vec.end());
struct Position { int x, y; };
// 如果 a < b 回傳 true, 反之 false
bool compare(const Position& a, const Position& b) {
return (a.x < b.x || (a.x == b.x && a.y < b.y));
}
Position pos[4]
std::sort(pos, pos + 4, compare);
std::next_permutation
下個字典序#include <algorithm>
int s[] = {1, 2, 3};
do {
std::cout << s << std::endl;
} while (std::next_permutation(s, s + 3));