動態編譯仿函數
1. call [eax]這樣的動態調用 在C++中是如何體現的
1、函數指針
typedef int (*func_t)(int, int);
int f(int a, int b)
{
return a + b;
}
int g(func_t f, int a, int b)
{
return f(a, b);
}
int main()
{
printf("%d\n", g(f, 1, 2));
}
2、函數對象(C++11或TR1)
#include <functional> //#include <tr1/functional>
using namespace std;
//using namespace std::tr1;
int f(int a, int b)
{
return a + b;
}
int g(function<int(int,int)> f, int a, int b)
{
return f(a, b);
}
int main()
{
printf("%d\n", g(f, 1, 2));
}
方法2所使用的對象可以與仿函數共同工作,但速度比方法1慢(類型擦除導致虛函數調用)
2. 地圖結構
#include <afx.h>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
struct Node
{
int nData;
Node *pNext;
Node(int initData=0, Node* p=NULL):nData(initData),pNext(p)
{
}
};
int main()
{
typedef map<CString ,Node > mapList;
mapList testMap;
CString strName;
Node theNode;
//the method 1 : using the make_pair and insert command insert to map
strName = "first";
theNode.nData = 1;
testMap.insert(make_pair(strName,theNode));
//the method 2 :Using the key insert to map
strName = "second";
theNode.nData = 2;
testMap[strName] = theNode;
mapList::const_iterator it;
mapList::iterator iter;
for(iter = testMap.begin();iter != testMap.end();++iter)
{
strName = (*iter).first;
theNode = (*iter).second;
cout<<"the key name is "<<strName.GetBuffer(0)<<endl;
cout<<"the node data is "<<theNode.nData<<endl;
}
return 0;
}
分析:插入map的結構方法有兩種,一種是insert函數法,配合使用make_pair很容易實現;還有一種就是索引法,用KEY做索引,testMap[strName] = theNode;也可以將其插入到map結構中。
---------------------------------------------------------------------------------------------------------------------------------
STL中map結構:
template <class Key, class T, class Compare = less<Key>, class Alloc = alloc>
第一個參數Key是關鍵字類型
第二個參數T是值類型
第三個參數Compare是比較函數(仿函數)
第四個參數是內存配置對象
map內部存儲機制實際是以紅黑樹為基礎,紅黑樹在插入節點時,必須依照大小比對之後在一個合適的位置上執行插入動作。所以作為關鍵字,起碼必須有「<」這個比較操作符。但是復雜數據類型或者自定義類型struct,class等,如果沒有明確定義「<」比較操作符,就不能與map直接搭配使用,或者在類型定義結構中重載定義「<」比較操作符,或者自己定義第三個參數。
在選擇map的關鍵字時,注意以下兩點,同時這兩點也是改錯的方法:
a) 關鍵字明確定義「<」比較操作符
b) 沒有「<」比較操作符,自定義仿函數替代第三個參數Compare,該仿函數實現「()」操作符,提供比較功能。插入時各節點順序以該仿函數比較。
STL中map結構:
template <class Key, class T, class Compare = less<Key>, class Alloc = alloc>
第一個參數Key是關鍵字類型
第二個參數T是值類型
第三個參數Compare是比較函數(仿函數)
第四個參數是內存配置對象
map內部存儲機制實際是以紅黑樹為基礎,紅黑樹在插入節點時,必須依照大小比對之後在一個合適的位置上執行插
入動作。所以作為關鍵字,起碼必須有「<」這個比較操作符。但是復雜數據類型或者自定義類型struct,class等,
如果沒有明確定義「<」比較操作符,就不能與map直接搭配使用,除非自己定義第三個參數。
在選擇map的關鍵字時,注意以下兩點,同時這兩點也是改錯的方法:
a) 關鍵字明確定義「<」比較操作符
b) 沒有「<」比較操作符,自定義仿函數替代第三個參數Compare,該仿函數實現「()」操作符,提供比較功能。
插入時各節點順序以該仿函數為綱。
1.以std::pair為關鍵字插入map
struct comp
{
typedef std::pair<int, int> value_type;
bool operator () (const value_type & ls, const value_type &rs) const
{
return ls.first < rs.first || (ls.first == rs.first && ls.second < rs.second);
}
};
int main()
{
std::map<std::pair<int, int>, int, comp> testMap;
testMap.insert(std::make_pair(std::make_pair(1,2), 3));
testMap.insert(std::make_pair(std::make_pair(11,22), 33));
testMap.insert(std::make_pair(std::make_pair(111,222), 333));
std::map<std::pair<int, int>, int, comp>::iterator it = testMap.find(std::make_pair(111,222));
if (it == testMap.end())
cout<<"The key is not in the map."<<endl;
else
cout<<"the key value is :"<<it->first.first<<","<<it->first.second<<endl
<<"the nonkey value is"<<it->second<<endl;
return 0;
}
分析:pair結構中沒有明確定義"<"比較操作符,如果不定義比較函數的comp,而直接插入就會編譯出錯。這里我們
定義了一個外部的比較函數是實現"()"比較操作符.
2.以結構體或類為關鍵字插入map
struct Node
{
string strKey;
int nKeyData;
Node(string stmp,int ntmp=0):strKey(stmp),nKeyData(ntmp){}
bool operator < (const Node &rhs) const
{
return strKey<rhs.strKey;
}
};
int main()
{
std::map<struct Node, int> testMap;
testMap.insert(std::make_pair(Node("test1",1), 3));
testMap.insert(std::make_pair(Node("test2",2), 33));
testMap.insert(std::make_pair(Node("test3",22), 333));
std::map<struct Node, int>::iterator it = testMap.find(Node("test2",2));
if (it == testMap.end())
cout<<"The key is not in the map."<<endl;
else
cout<<"the key value is :"<<it->first.strKey<<","<<it->first.nKeyData<<endl
<<"the nonkey value is "<<it->second<<endl;
return 0;
}
分析:注意operator < (const Node &rhs) const ,一定要按照這個形式來寫,少一個const都會報錯。原因在於map<struct Node, int> testMap 定義時,結構體中的「<」在less調用這個比較符時,它都是以const方式傳入,不可能再以非const方式調用,故出錯。
剛剛給出的例子,是在struct結構中定義了'<' 操作符:bool operator < (const Node &rhs) const 。除此之外,我們還可以用另一種方法,內聯函數的方法解決以上出現的問題:
struct Node
{
string strKey;
int nKeyData;
Node(string stmp,int ntmp=0):strKey(stmp),nKeyData(ntmp){}
friend bool operator < (const struct Node &lhs, const struct Node &rhs);
// bool operator < (const Node &rhs) const
// {
// return strKey<rhs.strKey;
// }
};
inline bool operator < (const struct Node &lhs, const struct Node &rhs)
{
return lhs.strKey<rhs.strKey;
}
PS:
在map容器中插入數據有很多函數可用,這里只討論最普通的insert操作,在STL中它是這樣定義的。
pair<iterator, bool> insert(const value_type& x);
map容器不允許鍵值重復,在執行插入操作後,可以憑借該返回值獲取操作結果。返回值是一個迭代器和布爾值的鍵值對,迭代器指向map中具有該值的元素,布爾值表示是否插入成功。如果布爾值為true,表示插入成功,則迭代器為新插入值在map中的位置;布爾值為false,表示插入失敗(已經存在該值),迭代器為原有值在map中的位置。
3. c++語言sort函數問題,為什麼編譯錯誤求助
1)sort()的第三個參數,是一個比較函數(或仿函數),這個比較函數的返回值應該是bool型的。
2)sort()內部在排序的時候,會用賦值符號"=",來對元素進行順序調整,而你的元素是char[100]型的,是不能用"="來賦值的(char[]數組一般是用strcpy()來賦值的)。
3)while(scanf("%d",&n)&&n) 會引起死循環。因為讀到文件末尾的話,scanf()會返回-1。
改正後的代碼如下:
#include<cstdlib>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include <algorithm>
#include<set>
#include<vector>
#define inf 0x7fffffff
#define E 1e-9
#define N 25
using namespace std;
string a[N];
int n;
bool cmp(const string &a, const string &b)
{
string aa, bb;
aa = a + b;
bb = b + a;;
return aa < bb;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("ex.in","r",stdin);
#endif
while( scanf("%d",&n) == 1 && n )
{
for(int i=0;i<n;++i)
{
char tmp[100];
scanf("%s",tmp);
a[i] = tmp;
}
sort( a, a+n, cmp );
for(int i=0;i<n;++i)
printf("%s",a[i].c_str());
printf("\n");
}
return 0;
}
4. 電腦里常用的的英語有那些(漢語意思)
硬體類(Hardware)
軟體類(Software)
網路類(Network)
CPU(Center Processor Unit)中央處理單元
mainboard主板
RAM(random access
memory)隨機存儲器(內存)
ROM(Read Only Memory)只讀存儲器
Floppy Disk軟盤
Hard Disk硬碟
CD-ROM光碟驅動器(光碟機)
monitor監視器
keyboard鍵盤
mouse滑鼠
chip晶元
CD-R光碟刻錄機
HUB集線器
Modem= MOlator-DEMolator,數據機
P-P(Plug and Play)即插即用
UPS(Uninterruptable Power Supply)不間斷電源
BIOS(Basic-input-Output
System)基本輸入輸出系統
CMOS(Complementary Metal-Oxide-Semiconctor)互補金屬氧化物半導體
setup安裝
uninstall卸載
wizzard向導
OS(Operation Systrem)操作系統
OA(Office AutoMation)辦公自動化
exit退出
edit編輯
復制
cut剪切
paste粘貼
delete刪除
select選擇
find查找
select all全選
replace替換
undo撤消
redo重做
program程序
license許可(證)
back前一步
next下一步
finish結束
folder文件夾
Destination Folder目的文件夾
user用戶
click點擊
double click雙擊
right click右擊
settings設置
update更新
release發布
data數據
data base資料庫
DBMS(Data Base Manege
System)資料庫管理系統
view視圖
insert插入
object對象
configuration配置
command命令
document文檔
POST(power-on-self-test)電源自檢程序
cursor游標
attribute屬性
icon圖標
service pack服務補丁
option pack功能補丁
Demo演示
short cut快捷方式
exception異常
debug調試
previous前一個
column行
row列
restart重新啟動
text文本
font字體
size大小
scale比例
interface界面
function函數
access訪問
manual指南
active激活
computer language計算機語言
menu菜單
GUI(graphical user
interfaces )圖形用戶界面
template模版
page setup頁面設置
password口令
code密碼
print preview列印預覽
zoom in放大
zoom out縮小
pan漫遊
cruise漫遊
full screen全屏
tool bar工具條
status bar狀態條
ruler標尺
table表
paragraph段落
symbol符號
style風格
execute執行
graphics圖形
image圖像
Unix用於伺服器的一種操作系統
Mac OS蘋果公司開發的操作系統
OO(Object-Oriented)面向對象
virus病毒
file文件
open打開
colse關閉
new新建
save保存
exit退出
clear清除
default默認
LAN區域網
WAN廣域網
Client/Server客戶機/伺服器
ATM( Asynchronous
Transfer Mode)非同步傳輸模式
Windows NT微軟公司的網路操作系統
Internet互聯網
WWW(World Wide Web)萬維網
protocol協議
HTTP超文本傳輸協議
FTP文件傳輸協議
Browser瀏覽器
homepage主頁
Webpage網頁
website網站
URL在Internet的WWW服務程序上
用於指定信息位置的表示方法
Online在線
Email電子郵件
ICQ網上尋呼
Firewall防火牆
Gateway網關
HTML超文本標識語言
hypertext超文本
hyperlink超級鏈接
IP(Address)互聯網協議(地址)
SearchEngine搜索引擎
TCP/IP用於網路的一組通訊協議
Telnet遠程登錄
IE(Internet Explorer)探索者(微軟公司的網路瀏覽器)
Navigator引航者(網景公司的瀏覽器)
multimedia多媒體
ISO國際標准化組織
ANSI美國國家標准協會
able 能
activefile 活動文件
addwatch 添加監視點
allfiles 所有文件
allrightsreserved 所有的權力保留
altdirlst 切換目錄格式
並能夠解決更大范圍內的磁碟問題
andotherinFORMation 以及其它的信息
archivefileattribute 歸檔文件屬性
assignto 指定到
autoanswer 自動應答
autodetect 自動檢測
autoindent 自動縮進
autosave 自動存儲
availableonvolume 該盤剩餘空間
badcommand 命令錯
badcommandorfilename 命令或文件名錯
batchparameters 批處理參數
binaryfile 二進制文件
binaryfiles 二進制文件
borlandinternational borland國際公司
bottommargin 頁下空白
bydate 按日期
byextension 按擴展名
byname 按名稱
bytesfree 位元組空閑
callstack 調用棧
casesensitive 區分大小寫
要求出現確認提示,在你想覆蓋一個
centralpointsoftwareinc central point 軟體股份公司
changedirectory 更換目錄
changedrive 改變驅動器
changename 更改名稱
characterset 字元集
checkingfor 正在檢查
檢查磁碟並顯示一個狀態報告
chgdrivepath 改變盤/路徑
china 中國
chooseoneofthefollowing 從下列中選一項
clearall 全部清除
clearallbreakpoints 清除所有斷點
clearsanattribute 清除屬性
clearscommandhistory 清除命令歷史
clearscreen 清除屏幕
closeall 關閉所有文件
codegeneration 代碼生成
colorpalette 彩色調色板
commandline 命令行
commandprompt 命令提示符
compressedfile 壓縮文件
配置硬碟,以為 MS-DOS 所用
conventionalmemory 常規內存
***ceptemptyones 拷貝目錄和子目錄,空的除外
拷貝設置了歸檔屬性的文件
把文件拷貝或搬移至另一地方
把一個軟盤的內容拷貝到另一個軟盤上
diskette 復制磁碟
C拷貝M移動 O比 F搜索R改名 D刪除 V版本 E瀏覽A屬性 W寫字 P列印 L列表
rightc 版權(c
創建DOS分區或邏輯DOS驅動器
createextendeddospartition 創建擴展DOS分區
在擴展DOS分區中創建邏輯DOS驅動器
createprimarydospartition 創建DOS主分區
createsadirectory 創建一個目錄
創建,改變或刪除磁碟的卷標
currentfile 當前文件
currentfixeddiskdrive 當前硬碟驅動器
currentsettings 當前設置
currenttime 當前時間
cursorposition 游標位置
defrag 整理碎片
dele 刪去
刪除分區或邏輯DOS驅動器
刪除一個目錄和所有的子目錄及其中的所有文件
deltree 刪除樹
devicedriver 設備驅動程序
dialogbox 對話欄
directionkeys 方向鍵
directly 直接地
directorylistargument 目錄顯示變數
directoryof 目錄清單
directorystructure 目錄結構
diskaccess 磁碟存取
disk 磁碟拷貝
磁碟服務功能: C拷貝 O比較 F搜索R改卷名V校驗 瀏覽E編緝M圖 L找文件 N格式化
diskspace 磁碟空間
displayfile 顯示文件
displayoptions 顯示選項
displaypartitioninFORMation 顯示分區信息
顯示指定目錄和所有目錄下的文件
顯示指定屬性的文件
顯示或改變文件屬性
displaysorsetsthedate 顯示或設備日期
以單色而非彩色顯示安裝屏信息
顯示系統中已用和未用的內存數量
顯示磁碟上所有文件的完整路徑和名稱
顯示或改變當前目錄
doctor 醫生
doesn 不
doesntchangetheattribute 不要改變屬性
dosshell DOS 外殼
doubleclick 雙擊
你想顯示邏輯驅動器信息嗎(y/n)?
driveletter 驅動器名
editmenu 編輯選單
emsmemory ems內存
endoffile 文件尾
endofline 行尾
enterchoice 輸入選擇
entiredisk 轉換磁碟
environmentvariable 環境變數
esc esc
everyfileandsubdirectory 所有的文件和子目錄
existingdestinationfile 已存在的目錄文件時
expandedmemory 擴充內存
expandtabs 擴充標簽
explicitly 明確地
extendedmemory 擴展內存
fastest 最快的
fatfilesystem fat 文件系統
fdiskoptions fdisk選項
fileattributes 文件屬性
fileFORMat 文件格式
filefunctions 文件功能
fileselection 文件選擇
fileselectionargument 文件選擇變元
filesin 文件在
filesinsubdir 子目錄中文件
fileslisted 列出文件
filespec 文件說明
filespecification 文件標識
filesselected 選中文件
findfile 文件查尋
fixeddisk 硬碟
fixeddisksetupprogram 硬碟安裝程序
fixeserrorsonthedisk 解決磁碟錯誤
floppydisk 軟盤
FORMatdiskette 格式化磁碟
FORMatsadiskforusewithmsdos 格式化用於MS-DOS的磁碟
FORMfeed 進紙
freememory 閑置內存
fullscreen 全屏幕
functionprocere 函數過程
graphical 圖解的
graphicslibrary 圖形庫
groupdirectoriesfirst 先顯示目錄組
hangup 掛斷
harddisk 硬碟
hardwaredetection 硬體檢測
ha**een 已經
helpfile 幫助文件
helpindex 幫助索引
helpinFORMation 幫助信息
helppath 幫助路徑
helpscreen 幫助屏
helptext 幫助說明
helptopics 幫助主題
helpwindow 幫助窗口
hiddenfile 隱含文件
hiddenfileattribute 隱含文件屬性
hiddenfiles 隱含文件
howto 操作方式
ignorecase 忽略大小寫
在常規和上位內存
incorrectdos 不正確的DOS
incorrectdosversion DOS 版本不正確
indicatesabinaryfile 表示是一個二進制文件
indicatesanasciitextfile 表示是一個ascii文本文件
insertmode 插入方式
請用scandisk,不要用chkdsk
inuse 在使用
invaliddirectory 無效的目錄
is 是
kbytes 千位元組
keyboardtype 鍵盤類型
labeldisk 標注磁碟
laptop 膝上
largestexecutableprogram 最大可執行程序
largestmemoryblockavailable 最大內存塊可用
lefthanded 左手習慣
leftmargin 左邊界
linenumber 行號
linenumbers 行號
linespacing 行間距
listbyfilesinsortedorder 按指定順序顯示文件
listfile 列表文件
listof 清單
locatefile 文件定位
lookat 查看
lookup 查找
macroname 宏名字
makedirectory 創建目錄
memoryinfo 內存信息
memorymodel 內存模式
menubar 菜單條
menucommand 菜單命令
menus 菜單
messagewindow 信息窗口
microsoft 微軟
microsoftantivirus 微軟反病毒軟體
microsoftcorporation 微軟公司
mini 小的
modemsetup 數據機安裝
molename 模塊名
monitormode 監控狀態
monochromemonitor 單色監視器
moveto 移至
multi 多
newdata 新建數據
newer 更新的
newfile 新文件
newname 新名稱
newwindow 新建窗口
norton norton
nostack 棧未定義
noteusedeltreecautiously 注意:小心使用deltree
onlinehelp 聯機求助
optionally 可選擇地
or 或
pageframe 頁面
pagelength 頁長
在顯示每屏信息後暫停一下
pctools pc工具
postscript 附言
prefixmeaningnot 前綴意即"不
prefixtoreverseorder 反向顯示的前綴
presetche** 用前綴和放在短橫線-後的開關(例如/-w)預置開關
pressakeytoresume 按一鍵繼續
pressanykeyforfilefunctions 敲任意鍵執行文件功能
pressentertokeepthesamedate 敲回車以保持相同的日期
pressentertokeepthesametime 敲回車以保持相同的時間
pressesctocontinue 敲esc繼續
pressesctoexit 敲鍵退出
pressesctoexitfdisk 敲esc退出fdisk
敲esc返回fdisk選項
5. 為什麼c++14把random_shuffle標為deprecated
random_shuffle有兩種形式,即
template<classRandomAccessIterator>
voidrandom_shuffle(RandomAccessIteratorfirst,RandomAccessIteratorlast);
和
template<classRandomAccessIterator,classRandomNumberGenerator>
voidrandom_shuffle(RandomAccessIteratorfirst,RandomAccessIteratorlast,
RandomNumberGenerator&&rnd);
二者被deprecated(即不推薦使用)的原因並不一樣。
前者使用編譯器指定的隨機數發生器來打亂數組的內容,這個隨機數發生器通常是rand函數,它被deprecated的原因也和rand函數有關。由於rand函數是C語言的遺留產物,不同編譯器實現方法不一樣,產生隨機數的可靠性也千差萬別,並且C++11提供了一整套明確規定了演算法的隨機數發生器(位於<random>頭文件)。有人提議把rand函數標為deprecated,來讓更多的人使用C++11提供的「更好的東西」。使用rand函數的random_shuffle也被連帶標為deprecated。
後者要求rnd仿函數(只能是仿函數)產生的隨機數的范圍就是數組的下標范圍,這樣的仿函數通常不是很容易寫,完全可以被更好的東西代替——這個更好的東西就是shuffle函數
shuffle函數與random_shuffle的第二種形式相似,同樣是接受一個仿函數,但對隨機數的范圍要求更松,因而可以直接傳一個std::mt19997對象,或者std::random_device對象(都是C++11直接提供的隨機數發生器)的進去,更便於使用,同時不像rand一樣,不能保證打亂結果的可靠性
6. C++容器類中參數列表如何調用
一、STL容器類
STL(Standard
Template
Library)的六大組件:容器(containers)、迭代器(iterators)、空間配置器(allocator)、配接器(adapters)、演算法(algorithms)、仿函數(functors)六個部分。其交互關系:容器通過空間配置器取得數據存儲空間,空間配置器通過迭代器存取容器的內容,仿函數可以協助空間配置器完成不同的策略變化,配接器可以修飾或套接仿函數。
C++中的容器類包括「順序存儲結構」和「關聯存儲結構」,前者包括vector,list,deque等;後者包括set,map,multiset,multimap等。若需要存儲的元素數在編譯器間就可以確定,可以使用數組來存儲,否則,就需要用到容器類了。
1、vector
連續存儲結構,每個元素在內存上是連續的;
支持高效的隨機訪問和在尾端插入/刪除操作,但其他位置的插入/刪除操作效率低下;
2、deque
連續存儲結構,即其每個元素在內存上也是連續的,類似於vector,不同之處在於,deque提供了兩級數組結構,第一級完全類似於vector,代表實際容器;另一級維護容器的首位地址。
這樣,deque除了具有vector的所有功能外,還支持高效的首端插入/刪除操作。
3、list
非連續存儲結構,具有雙鏈表結構,每個元素維護一對前向和後向指針,因此支持前向/後向遍歷。
支持高效的隨機插入/刪除操作,但隨機訪問效率低下,且由於需要額外維護指針,開銷也比較大。
4、vector
--
list
--
deque:
a、若需要隨機訪問操作,則選擇vector;
b、若已經知道需要存儲元素的數目,
則選擇vector;
c、若需要隨機插入/刪除(不僅僅在兩端),則選擇list
d、只有需要在首端進行插入/刪除操作的時候,才選擇deque,否則都選擇vector。
e、若既需要隨機插入/刪除,又需要隨機訪問,則需要在vector與list間做個折中。
f、當要存儲的是大型負責類對象時,list要優於vector;當然這時候也可以用vector來存儲指向對象的指針,同樣會取得較高的效率,但是指針的維護非常容易出錯,因此不推薦使用。
5、capacity
--
size
a、capacity是容器需要增長之前,能夠盛的元素總數;只有連續存儲的容器才有capacity的概念(例如vector,deque,string),list不需要capacity。
b、size是容器當前存儲的元素的數目。
c、vector默認的容量初始值,以及增長規則是依賴於編譯器的。
6、用vector存儲自定義類對象時,自定義類對象須滿足:
a、有可供調用的無參構造函數(默認的或自定義的);
b、有可用的拷貝賦值函數(默認的或自定義的)