原文請訪問我的博客:http://xiaoshig.sinaapp.com/
向上取整
使用ceil函數。ceil(x)返回的是大於x的最小整數。如: ceil(2.5) = 3 ceil(-2.5) = -2sort排序頭文件
#include <algorithm>
數組初始化總結
整型數組初始化://只能賦值0,賦其他值用memset(a,要賦的值,sizeof(a));
char a[3][4]={0};
字符數組初始化:
int b[3][4]={0};
布爾型數組初始化:
bool c[5]={0};
結構體初始化:
struct instruction{ //定義結構體,存儲指令
int head; //識別指令
int d;
int n; //指令附加內容
}pro[1000]={0}; //存儲程序體,相當於RAM
初始化之後都會變成0。
(char數組變爲\000,int數組變爲0,bool數組變爲false,這個例子裏的結構體所有元素的每一個成員值都爲0)
sort()函數的使用
sort()和qsort()一樣,都是對數組的指定部分排序。qsort()只使用了快排,sort()使用了混合排序,相比之下,sort()更快一些。
sort()函數常用的有兩種形式,兩個參數的形式,和三個參數的形式。
1、兩參數:sort(數組名,數組末地址); //例如:sort(a+1,a+n+1);就是對a[1]...a[n+1]進行排序,默認是升序排序,如果想改變排序順序,需要另寫一個比較函數
2、三參數:sort(數組名,數組末地址,比較函數);
例如:
bool cmp(const int a,const int b)
{
return a<b;
}
sort(a+1,a+10+1,cmp);
就是對a[1]...a[n+1]進行從大到小排序。
string類庫
substr 方法
返回一個從指定位置開始的指定長度的子字符串。 stringvar.substr(start [開始的數, length ]) 參數 stringvar 必選項。要提取子字符串的字符串文字或 String 對象。 start 必選項。所需的子字符串的起始位置。字符串中的第一個字符的索引爲 0。 length 可選項。在返回的子字符串中應包括的字符個數。 說明 如果 length 爲 0 或負數,將返回一個空字符串。如果沒有指定該參數,則子字符串將延續到 stringvar 的最後。
示例 下面的示例演示了substr 方法的用法。
<pre name="code" class="cpp">function SubstrDemo()
{ var s, ss; //聲明變量。
var s = "The rain in Spain falls mainly in the plain.";
ss = s.substr(12, 5); //獲取子字符串。
return(ss);
//返回 "Spain"。
查找字符串a是否包含子串b,不是用strA.find(strB) > 0而是strA.find(strB) != string:npos
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int student_Score[] = { 50,80,93,23,66};
void pritit(int nScore)
{
cout<<nScore<<" ";
}
bool unPass(int nScore)
{
return nScore < 60;
}
bool Pass(int nScore)
{
return nScore >= 60;
}
int main(int argc, char* argv[])
{
vector<int> v_score(student_Score,student_Score+sizeof(student_Score)/sizeof(int));
vector<int>::iterator index;
//排序
sort(v_score.begin(),v_score.end());
//顯示
for_each(v_score.begin(),v_score.end(),pritit); cout<<endl;
//顯示最小
index = min_element(v_score.begin(),v_score.end());
cout<<"最小分數 "<<*index<<endl;
//顯示最大
index = max_element(v_score.begin(),v_score.end());
cout<<"最大分數 "<<*index<<endl;
//顯示不低於60分的數量
cout<<"低於60的數量 " <<count_if(v_score.begin(),v_score.end(),unPass)<<endl;
//高於60的數量
cout<<"高於60的數量 "<<count_if(v_score.begin(),v_score.end(),Pass)<<endl;
//平均數
int sum = 0;
for (index = v_score.begin(); index != v_score.end(); index++)
{
sum += *index;
}
cout<<"平均數 "<<sum / v_score.size() <<endl;
return 0;
}