Abstract
若需要將程式碼放進(jìn)word交報(bào)告或做文件時(shí),或許我們會(huì)想將程式碼加上行號(hào)方便講解,如同博客園顯示程式碼那樣,我們?cè)撊绾巫瞿?
Introduction
使用環(huán)境:Visual C++ 9.0 / Visual Studio 2008
一段C++的小程式,可以幫程式碼加上行號(hào)后輸出。
以下為引用的內(nèi)容:
map_code_line.cpp / C++
復(fù)制代碼 代碼如下:
/*
(C) OOMusou 2008
Filename : map_code_line.cpp
Compiler : Visual C++ 9.0 / Visual Studio 2008
Description : Demo how to add line number for code
Release : 07/18/2008 1.0
*/
#include iostream>
#include fstream>
#include string>
#include map>
#include algorithm>
using namespace std;
ifstream infile("map_code_line.cpp");
ofstream outfile("map_code_line_r.cpp");
struct print_map {
void operator() (pairint, string> p) {
cout p.first " " p.second endl;
outfile p.first " " p.second endl;
}
};
int main() {
mapint, string> lines;
string line;
int line_num = 1;
while(getline(infile, line))
lines[line_num++] = line;
infile.close();
for_each(lines.begin(), lines.end(), print_map());
outfile.close();
}
執(zhí)行結(jié)果
以下為引用的內(nèi)容:
復(fù)制代碼 代碼如下:
/*
(C) OOMusou 2008 http://oomusou.cnblogs.com
Filename : map_code_line.cpp
Compiler : Visual C++ 9.0 / Visual Studio 2008
Description : Demo how to add line number for code
Release : 07/18/2008 1.0
*/
#include iostream>
#include fstream>
#include string>
#include map>
#include algorithm>
using namespace std;
ifstream infile("map_code_line.cpp");
ofstream outfile("map_code_line_r.cpp");
struct print_map {
void operator() (pairint, string> p) {
cout p.first " " p.second endl;
outfile p.first " " p.second endl;
}
};
int main() {
mapint, string> lines;
string line;
int line_num = 1;
while(getline(infile, line))
lines[line_num++] = line;
infile.close();
for_each(lines.begin(), lines.end(), print_map());
outfile.close();
}
32行
以下為引用的內(nèi)容:
復(fù)制代碼 代碼如下:
while(getline(infile, line))
lines[line_num++] = line;
是整個(gè)程式的關(guān)鍵:使用map,key存放行號(hào),value存放每一行的程式碼。而且隨著每一行程式碼的讀入,自動(dòng)增加行號(hào)。
37行
以下為引用的內(nèi)容:
復(fù)制代碼 代碼如下:
for_each(lines.begin(), lines.end(), print_map());
將map內(nèi)容印出,因?yàn)閙ap無(wú)法配合copy(),只好退而求其次使用for_each()與functor。
20行
以下為引用的內(nèi)容:
復(fù)制代碼 代碼如下:
struct print_map {
void operator() (pairint, string> p) {
cout p.first " " p.second endl;
outfile p.first " " p.second endl;
}
};
配合for_each()的functor,22行的cout可以拿掉,只是方面在螢?zāi)伙@示而已。
Conclusion
STL的map是很好用的容器,尤其substring寫(xiě)法,若index下沒(méi)有元素,會(huì)自動(dòng)新增,所以才會(huì)有l(wèi)ines[line_number++] = line;這麼漂亮的寫(xiě)法。
您可能感興趣的文章:- dhtmlxGrid 添加行號(hào)詳細(xì)步驟
- DataGridView控件顯示行號(hào)的正確代碼及分析
- FLEX 獲取DataGrid行號(hào)和列號(hào)示例代碼
- python中使用sys模板和logging模塊獲取行號(hào)和函數(shù)名的方法
- pycharm 使用心得(四)顯示行號(hào)
- Python實(shí)現(xiàn)去除代碼前行號(hào)的方法
- MyEclipse刪除網(wǎng)上復(fù)制下來(lái)的來(lái)代碼帶有的行號(hào)(正則去除行號(hào))