前言:本認爲這只是一本教授C++基本語法的小書,仔細翻看過一遍,裏面涵蓋了C++大部分常用的知識,有些程序和建議都非常精妙,貝海拾遺,恐以後忘記,故書寫以記之。
1.rand()函數
下面是隨機產生色子隨機數的例子:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));//爲隨機數生成器設置種子
int randomNumber = rand();
int num = (randomNumber % 6) + 1;//die的範圍爲1~6
cout << "你搖的色子的數字是:" << num << endl;
return 0;
}
rand函數的使用:rand()在cstdlib頭文件中,它生成從0到32767之間的隨機數。具體的上界取決於所使用的C++實現。該上界存儲在cstdlib定義的常量RAND_MAX中。可以把RAND_MAX發送給cout。
計算機基於數學公式生成的時僞隨機數,而不是真正的隨機數。可以把這想象成讓計算機從一本包含許多數字的書中讀取數字。通過從該書中讀取,計算機可以表現的像是在產生隨機數序列。
但是這樣存在一個問題:計算機總是從書的起始點讀取數字。因此,計算機在程序中總是產生相同的“隨機數序列”。
這個問題的解決方法是:告訴計算機從書的某個任意位置開始讀取數字。該過程成爲爲隨機數生成器確定種子。程序員爲隨機數生成器提供一個叫做種子的數來確定僞隨機數序列的起始位置。
下面的代碼爲隨機數生成器確定種子。
srand(static_cast<unsigned int>(time(0)));//爲隨機數生成器設置種子
它基於當前日期和事件爲生成器確定種子。
srand()函數爲生成器確定種子,它接收一個unsigned int型的值作爲種子。
2.將字符串亂序
法I:對字符串取地址
//實現string單詞亂序
for (int i=0; i<length; ++i)
{
int index1 = (rand() % length);//生成隨機值
int index2 = (rand() % length);
char temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
}
程序生成string對象中的兩個隨機位置,並交換兩個位置的字符。交換操作的次數等於單詞的長度。法II:random_shuffle()
vector<string> words; // collection of possible words to guess
words.push_back("GUESS");
words.push_back("HANGMAN");
words.push_back("DIFFICULT");
srand(static_cast<unsigned int>(time(0)));
random_shuffle(words.begin(), words.end());//shuffle:洗牌,隨手放,搬移
random_shuffle用於打亂向量或字符串中的順序。詳細內容參見定義:The function swaps the value of each element with that of some other randomly chosen element. When provided, the function rand chooses which element.
另外,random_shuffle還可以處理其它類型數組:
int n[4] = {0,1,2,3};
random_shuffle(n, n+4);
3.動態分配內存
動態分配內存時較好的編程方法:
int* pHeap = new int;
*pHeap = 10;
int* pHeap2 = new int[20];
delete pHeap;
delete pHeap2;
pHeap = 0;
pHeap2 = 0;
因爲需要釋放掉不再使用的已經分配過的內存,所以一個較好的準則但是每個new都應當有一個響應的delete。實際上,有些程序員儘可能編寫new語句之後就編寫delete語句,這樣就不會忘記釋放內存。
int* pHeap = new int;
*pHeap = 10;
int* pHeap2 = new int[20];
delete pHeap;
delete pHeap2;
重點:上面的兩條語句釋放掉堆中的內存,但是他們沒有直接影響到局部變量pHeap和pHeap2。這造成一個潛在的問題,因爲pHeap和pHeap2現在指向已經返回給堆的內存,即它們所指向計算機可能在任意某個時刻以某種方式使用的內存。像這樣的指針成爲野指針,它們相當危險,絕不應當對它們解引用。
一種處理野指針的方法是將它們賦值爲0.使得它們不再指向不應當使用的內存。
pHeap = 0;
pHeap2 = 0;
如需轉載,請註明出處:http://blog.csdn.net/rehongchen/article/details/8038551