正在处理您的请求...
<script language="javascript" type="text/javascript">
</script>
element block and removes
// previous instances of the identical script.
var found = false;
for (var child = 0; child < head.childNodes.length; child++) {
var control = head.childNodes[child];
if (control.tagName.toUpperCase() == "SCRIPT") {
if (script.src.length > 0) {
if (script.src == control.src) {
found = true;
break;
}
} else if (script.innerHTML.length > 0) {
if (script.innerHTML == control.innerHTML) {
found = true;
break;
}
}
}
}
if (found) {
head.removeChild(control);
}
// Now we append the new script and move on to the next script.
// Note that this is a recursive function. It stops when the
// index grows larger than the number of scripts.
document.getElementsByTagName('head')[0].appendChild(script);
if (typeof script.readyState != "undefined") {
script.onreadystatechange = function() {
if (script.readyState != "complete" && script.readyState != "loaded") {
return;
} else {
Anthem_LoadPageScript(result, index + 1);
}
}
} else {
Anthem_LoadPageScript(result, index + 1);
}
}
} catch (e) {
Anthem_DebugError("Error adding page script to head. " + e.name + ": " + e.message);
}
}
}
function Anthem_EvalClientSideScript(result) {
if (result.script) {
for (var i = 0; i < result.script.length; ++i) {
try {
eval(result.script[i]);
} catch (e) {
alert("Error evaluating client-side script!/n/nScript: " + result.script[i] + "/n/nException: " + e);
}
}
}
}
function Anthem_DebugRequestText(text) {
}
function Anthem_DebugResponseText(text) {
}
function Anthem_DebugError(text) {
}
//Fix for bug #1429412, "Reponse callback returns previous response after file push".
//see http://sourceforge.net/tracker/index.php?func=detail&aid=1429412&group_id=151897&atid=782464
function Anthem_Clear__EVENTTARGET() {
var form = document.getElementById(Anthem_FormID);
Anthem_SetHiddenInputValue(form, "__EVENTTARGET", "");
}
function Anthem_InvokePageMethod(methodName, args, clientCallBack, clientCallBackArg) {
Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
return Anthem_CallBack(null, "Page", null, methodName, args, clientCallBack, clientCallBackArg, true, true);
}
function Anthem_InvokeMasterPageMethod(methodName, args, clientCallBack, clientCallBackArg) {
Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
return Anthem_CallBack(null, "MasterPage", null, methodName, args, clientCallBack, clientCallBackArg, true, true);
}
function Anthem_InvokeControlMethod(id, methodName, args, clientCallBack, clientCallBackArg) {
Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
return Anthem_CallBack(null, "Control", id, methodName, args, clientCallBack, clientCallBackArg, true, true);
}
function Anthem_PreProcessCallBack(
control,
e,
eventTarget,
causesValidation,
validationGroup,
imageUrlDuringCallBack,
textDuringCallBack,
enabledDuringCallBack,
preCallBackFunction,
callBackCancelledFunction,
preProcessOut
) {
preProcessOut.Enabled = !control.disabled;
var preCallBackResult = true;
if (preCallBackFunction) {
preCallBackResult = preCallBackFunction(control);
}
if (typeof(preCallBackResult) == "undefined" || preCallBackResult) {
var valid = true;
if (causesValidation && typeof(Page_ClientValidate) == "function") {
valid = Page_ClientValidate(validationGroup);
}
if (typeof(WebForm_OnSubmit) == "function") {
valid = WebForm_OnSubmit();
}
if (valid) {
var inputType = control.getAttribute("type");
inputType = (inputType == null) ? '' : inputType.toUpperCase();
if (inputType == "IMAGE" && e != null) {
var form = document.getElementById(Anthem_FormID);
if (e.offsetX) {
Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.offsetX);
Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.offsetY);
} else {
Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.clientX - control.offsetLeft + 1);
Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.clientY - control.offsetTop + 1);
}
}
if (imageUrlDuringCallBack || textDuringCallBack) {
if (control.nodeName.toUpperCase() == "INPUT") {
if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") {
preProcessOut.OriginalText = GetLabelText(control.id);
SetLabelText(control.id, textDuringCallBack);
} else if (inputType == "IMAGE") {
if (imageUrlDuringCallBack) {
preProcessOut.OriginalText = control.src;
control.src = imageUrlDuringCallBack;
} else {
preProcessOut.ParentElement = control.parentElement ? control.parentElement : control.parentNode;
if (preProcessOut.ParentElement) {
preProcessOut.OriginalText = preProcessOut.ParentElement.innerHTML;
preProcessOut.ParentElement.innerHTML = textDuringCallBack;
}
}
} else if (inputType == "SUBMIT") {
preProcessOut.OriginalText = control.value;
control.value = textDuringCallBack;
}
} else if (control.nodeName.toUpperCase() == "SELECT") {
preProcessOut.OriginalText = GetLabelText(control.id);
SetLabelText(control.id, textDuringCallBack);
} else {
preProcessOut.OriginalText = control.innerHTML;
control.innerHTML = textDuringCallBack;
}
}
control.disabled = (typeof enabledDuringCallBack == "undefined") ? false : !enabledDuringCallBack;
return true;
} else {
return false;
}
} else {
if (callBackCancelledFunction) {
callBackCancelledFunction(control);
}
return false;
}
}
function Anthem_PreProcessCallBackOut() {
// Fields
this.ParentElement = null;
this.OriginalText = '';
this.Enabled = true;
}
function Anthem_PostProcessCallBack(
result,
control,
eventTarget,
clientCallBack,
clientCallBackArg,
imageUrlDuringCallBack,
textDuringCallBack,
postCallBackFunction,
preProcessOut
) {
if (postCallBackFunction) {
postCallBackFunction(control);
}
control.disabled = !preProcessOut.Enabled;
var inputType = control.getAttribute("type");
inputType = (inputType == null) ? '' : inputType.toUpperCase();
if (inputType == "IMAGE") {
var form = document.getElementById(Anthem_FormID);
Anthem_RemoveHiddenInput(form, eventTarget + ".x");
Anthem_RemoveHiddenInput(form, eventTarget + ".y");
}
if (imageUrlDuringCallBack || textDuringCallBack) {
if (control.nodeName.toUpperCase() == "INPUT") {
if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") {
SetLabelText(control.id, preProcessOut.OriginalText);
} else if (inputType == "IMAGE") {
if (imageUrlDuringCallBack) {
control.src = preProcessOut.OriginalText;
} else {
preProcessOut.ParentElement.innerHTML = preProcessOut.OriginalText;
}
} else if (inputType == "SUBMIT") {
control.value = preProcessOut.OriginalText;
}
} else if (control.nodeName.toUpperCase() == "SELECT") {
SetLabelText(control.id, preProcessOut.OriginalText);
} else {
control.innerHTML = preProcessOut.OriginalText;
}
}
if (clientCallBack) {
clientCallBack(result, clientCallBackArg);
}
}
function Anthem_FireCallBackEvent(
control,
e,
eventTarget,
eventArgument,
causesValidation,
validationGroup,
imageUrlDuringCallBack,
textDuringCallBack,
enabledDuringCallBack,
preCallBackFunction,
postCallBackFunction,
callBackCancelledFunction,
includeControlValuesWithCallBack,
updatePageAfterCallBack
) {
var preProcessOut = new Anthem_PreProcessCallBackOut();
var preProcessResult = Anthem_PreProcessCallBack(
control,
e,
eventTarget,
causesValidation,
validationGroup,
imageUrlDuringCallBack,
textDuringCallBack,
enabledDuringCallBack,
preCallBackFunction,
callBackCancelledFunction,
preProcessOut
);
if (preProcessResult) {
Anthem_FireEvent(
eventTarget,
eventArgument,
function(result) {
Anthem_PostProcessCallBack(
result,
control,
eventTarget,
null,
null,
imageUrlDuringCallBack,
textDuringCallBack,
postCallBackFunction,
preProcessOut
);
},
null,
includeControlValuesWithCallBack,
updatePageAfterCallBack
);
}
}
function AnthemListControl_OnClick(
e,
causesValidation,
validationGroup,
textDuringCallBack,
enabledDuringCallBack,
preCallBackFunction,
postCallBackFunction,
callBackCancelledFunction,
includeControlValuesWithCallBack,
updatePageAfterCallBack
) {
var target = e.target || e.srcElement;
if (target.nodeName.toUpperCase() == "LABEL" && target.htmlFor != '')
return;
var eventTarget = target.id.split("_").join("$");
Anthem_FireCallBackEvent(
target,
e,
eventTarget,
'',
causesValidation,
validationGroup,
'',
textDuringCallBack,
enabledDuringCallBack,
preCallBackFunction,
postCallBackFunction,
callBackCancelledFunction,
true,
true
);
}
function GetLabelText(id) {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor == id) {
return labels[i].innerHTML;
}
}
return null;
}
function SetLabelText(id, text) {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor == id) {
labels[i].innerHTML = text;
return;
}
}
}
//]]> </script> <script type="text/javascript" src="http://blog.csdn.net/WebResource.axd?d=1wkz58Z1rsBL-eFHJPld5ERhyO-4qXtUzHp7Q1KwrOE1&t=632963535947587500"></script> <script type="text/javascript">
</script>
<script language="javascript" src="http://tag.csdn.net/urltag.aspx" type="text/javascript"></script> 作者tag:
c/c++ CSDN 推荐tag:
c++
tag
python
vector
source
<script type="text/javascript">function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script>
一位网友正在学校做课程设计题目,要求在一个文件中找到给定单词出现的位置并统计出现次数。这是一个比较简单的文本处理问题, 于是, 我给他用 python 写了一个,并打赌在5分钟内用不到30行程序解决问题。 我作到了,下面是程序:
if __name__=='__main__': file_name = raw_input('Input the file you want to find in:') try: in_file = open(file_name,'r') lines = in_file.readlines()
tag_tok = '' while tag_tok.upper() != 'Q': tag_tok = raw_input('Input the word you want to find(Q for quit):') if tag_tok.upper() != 'Q': count = 0 line_no = 0 for line in lines: line_no = line_no + 1 inline_cnt = line.count(tag_tok) count = count + inline_cnt if inline_cnt > 0: print 'Find %s %d time(s) in line :%d'%(tag_tok,inline_cnt,line_no) print line print '---------------------------------' print 'Total fount %s %d time(s)'%(tag_tok, count) except: print "Can't open file %s"%(file_name)
但是,这个网友还不满足非要一个 C++的程序,理由是他们老师不会python , 正好我也想试试用C++解决和python做下对比:
#include <fstream> #include <iostream> #include <string> #include <vector> #include <algorithm>
using namespace std;
int BruteFind(const char *x, int m, const char *y, int n ,vector<int>& colpos) { int i, j, cnt=0; /* Searching */ for (j = 0; j <= n - m; ++j) { for (i = 0; i < m && x == y[i + j]; ++i); if (i >= m){ colpos[cnt++] = j; if(cnt == colpos.size()) colpos.resize(cnt * 2); } } return cnt; }
int count_string(string source, string tag, vector<int>& colpos){ int find_cnt = 0; find_cnt = BruteFind(tag.c_str(), tag.size(), source.c_str(),source.size(),colpos);
return find_cnt; }
int main(){ string file_name, line; vector<string> lines; lines.resize(10); cout << "Input the file name:"; cin >> file_name; ifstream in_file; try{ in_file.open(file_name.c_str()); if(!in_file) throw(file_name); } catch(string file_name){ cout << "Fatal error: File not found."<<endl; exit(1); }
int line_count = 0; do{ getline(in_file, lines[line_count]); line_count ++; if(line_count == lines.size()){ lines.resize(line_count * 2); } }while(in_file.eof()==0); string tag_tok; vector<int> colpos; colpos.resize(10); do{ cout << "Input the word you want to find(Q for quit):"; cin >> tag_tok; if(tag_tok == "Q"){ break; } int count = 0, line_no = 0 , inline_count; for(line_no = 0 ;line_no < line_count ; line_no++){ inline_count = count_string(lines[line_no], tag_tok, colpos); count += inline_count; if(inline_count > 0){ cout << "Find " << tag_tok << " " << inline_count << " time(s) in line " << line_no ; cout << " , column pos is ( "; for(int i = 0 ;i< inline_count ;i++){ cout << colpos << ' '; } cout << " )" << endl; cout << lines[line_no] << endl; } } cout << "--------------------------------" <<endl; cout << "Total fount " << tag_tok << " " << count << " time(s)" << endl; }while(tag_tok != "Q"); in_file.close(); return 0; }
这个程序用了30分钟。
从程序长度和编程时间上,粗略对比下:
Python 5 分钟 22行
C++ 30 分钟 60多行
从这个简单的例子中可以大体看到 脚本语言与C++语言中在开发时的差异了。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=27682
<script type="text/javascript">function hide(){showComment();}</script>
特别推荐:
gameloft招聘php程序员 Gameloft成立于1999年的法国,同年成为该 Gameloft公司是世界领先的手机、游戏软件开发 ai 下围棋什么时候电脑能战胜人脑 中国围棋国手 大学教授告诉你 ai 北大青鸟(西安兆隆)聘.net培训师 在校生近两千人,在职员工100余名,规模上已发展成 西安最大的软件工程师网络工程师培训基地之一 ai 青娱乐招聘高级运维工程师 “青娱乐”Qyule.com是国内领先的网络视频网 ai 主机完全DIY,域名免费试用 时代互联100M主机 216元/年 ai
<script type="text/javascript">document.write("
");</script>
<script language="javascript" type="text/javascript"> ad_width=468; ad_height=60; adcss=2; unionuser=19; ad_type='j'; count=5; </script> <script type="text/javascript" src="http://tagegg.csdn.net/showads.js" language="javascript"></script> <script src="http://tagegg.csdn.net/b.aspx?action=displayad&unionuser=19&unionurl=http%3A%2F%2Fblog.csdn.net%2Falbertlee%2Farchive%2F2004%2F06%2F27%2F27682.aspx&adcss=2&ad_type=j&width=468&height=60&ad_color=&ad_color_border=&count=5" language="JavaScript1.1" type="text/javascript"></script>
<script type="text/javascript" src="http://blog.csdn.net/js/showgm.js" language="javascript"></script>
<script src="http://www.csdn.net/common/counter.js" type="text/javascript"></script>
width="0" scrolling="no" height="0" frameborder="no" src="http://www.csdn.net/ggmm/dd333.htm" border="0" name="myframe" id="myframe"> <script type="text/javascript">
</script>
<script type="text/javascript">
</script>
<script language="javascript" type="text/javascript">
</script>
我也想用C++实现一下试试看,但实在看不懂题目要求:
a. "给定单词出现的位置" 是不是所有出现的位置,位置以什么来表示,是单词在文件中的偏移吗?
b. 对于文本"aaa",这其中算有个几个"aa",是算一个,还是算两个,如果是算一个,是算前一个,还是算后一个?
而看您写的C++代码,说实话,变量太多,而且变量的作用域都非常的大,一时半会我也看不懂。
想通过运行您写的C++代码来反推出题目要求,可以在VC6.0中又编译不通过,遗憾。
你用了python中的count函数,而你在C++没有利用已有的类似函数,而是自己写算法,这当然没法比啦
C++的count函数统计的元素,而search函数才是查找子序列。
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string strFile, strTarget, strBuf;
vector<string> lines;
// get Data from file & console
cout<< "Input file Name : "; cin >> strFile; ifstream inFile(strFile.c_str());
if (!inFile) { cerr<< "Error when open file! halt!"; return -1; }
cout << "Input the word you want to find(Q for quit):";
cin >> strTarget; if (strTarget == "Q" || strTarget =="q" ) return 0;
do { getline( inFile, strBuf ); lines.push_back(strBuf);
} while (inFile.eof()==0);
// deal with data
int countInLine = 0, countTotal = 0, lineNo = 0;
for (vector<string>::iterator iter=lines.begin(); iter<lines.end(); iter++ ) {
string::size_type pos = 0; int prePos = 0; string strTmp;
while ( (pos = (*iter).find_first_of(' ',pos)) != string::npos) { // slipt words
strTmp = (*iter).substr(prePos, pos-prePos);
if (strTmp==strTarget) countInLine++; prePos = 1 + pos++; }
strTmp = (*iter).substr(prePos, pos-prePos); // deal with the last word
if (strTmp==
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
using namespace std;
struct SmileOnce
{
void operator()( const string& line )
{
cout << "LINE" << ++linenum << ' ';
for( char const* p=line.begin(); (p=search(p,line.end(),str.begin(),str.end()))!=line.end(); p+=str.length() )
{
cout << ',' << (p-line.begin()+1);
++num;
}
cout << endl;
}
SmileOnce( const string& s,size_t& n ) : str(s),linenum(0),num(n) {}
private:
const string& str;
size_t linenum;
size_t& num;
};
int main( int argc, char *argv[] )
{
// 已知条件
string filename = "D://test.txt";
string str = "abc";
// 开始处理
size_t num = 0;
for_each( istream_iterator<string>(ifstream(filename.c_str())),istream_iterator<string>(),SmileOnce(str,num) );
cout << "共找到" << num << "处." << endl;
return 0;
}
经VC++6.0和DevC++4948编译运行测试通过
class linestring : public string{};
inline istream& operator >>( istream& in, linestring& rch )
{
return getline( in, rch );
}
struct SmileOnce
{
void operator()( const string& line )
{
++linenum;
string::const_iterator p = search(line.begin(),line.end(),str.begin(),str.end());
if( p!=line.end() )
{
cout << "LINE" << linenum << ": " << (p-line.begin()+1);
++num;
p+=str.length();
for( ;(p=search(p,line.end(),str.begin(),str.end()))!=line.end(); p+=str.length() )
{
cout << ',' << (p-line.begin()+1);
++num;
}
cout << endl;
}
}
SmileOnce( const string& s,size_t& n ) : str(s),linenum(0),num(n) {}
private:
const string& str;
size_t linenum;
size_t& num;
};
int main( int argc, char *argv[] )
{
// 已知条件
string filename = "D://test.txt";
string str = "abc";
// 开始处理
size_t num = 0;
ifstream file( filename.c_
不过我也使接触C++好长时间的人了,虽然没学好,但是这是不是从反面说明了Python的简单易学呢?
不错啊
#include<iostream.h>
#include<stdlib.h>
int rolldice(void);
main()
{
int sum,m,n,he,i,score,x;
unsigned seed;
cout<<"请输入一个随机的数字:";
cin>>seed;//输入随机数种子
srand(seed);//将种子传给RAND
for(n=1;n<=20;n++)
{
sum=rolldice();//第一轮计算和数
cin>>he;
if(he==sum)
{cout<<"cougratulation,please do another question"<<endl;
n=n+1;
x=10;
}
else
{cout<<"请再输入一次:"<<endl;
cin>>he;
if(he==sum)
{cout<<"很好,你是对的:"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你还有最后依次机会,请你输入答案:"<<endl;
cin>>he;
if(he==sum)
{cout<<"是的,你是对的!"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你没有机会了"<<endl;
n=n+1;
x=0;
cout<<"正确的答案是:"<<sum<<endl;
}
}
}
} }//对和的值进行判断
int rolldice(void)
{int die1,die2,worksum,i,he;
char t;
for(i=1;i<=20;i++)
{
worksum=die1+die2;
die1=1+rand()%9;
die2=10-rand()%20;
worksum=die1+die2;//出题,输入结果,给出答案
if(die2>0)
t='+';
else
t='-';
cout<<"请运算"<<die1<<t<<die2<<'='<<endl;//列出公式
cout<<"请作答:"<<endl;
return worksum;
}
}
高手指教啊??
#include<iostream.h>
#include<stdlib.h>
int rolldice(void);
main()
{
int sum,m,n,he,i,score,x;
unsigned seed;
cout<<"请输入一个随机的数字:";
cin>>seed;//输入随机数种子
srand(seed);//将种子传给RAND
for(n=1;n<=20;n++)
{
sum=rolldice();//第一轮计算和数
cin>>he;
if(he==sum)
{cout<<"cougratulation,please do another question"<<endl;
n=n+1;
x=10;
}
else
{cout<<"请再输入一次:"<<endl;
cin>>he;
if(he==sum)
{cout<<"很好,你是对的:"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你还有最后依次机会,请你输入答案:"<<endl;
cin>>he;
if(he==sum)
{cout<<"是的,你是对的!"<<endl;
n=n+1;
x=10;
}
else
{cout<<"你没有机会了"<<endl;
n=n+1;
x=0;
cout<<"正确的答案是:"<<sum<<endl;
}
}
}
} }//对和的值进行判断
int rolldice(void)
{int die1,die2,worksum,i,he;
char t;
for(i=1;i<=20;i++)
{
worksum=die1+die2;
die1=1+rand()%9;
die2=10-rand()%20;
worksum=die1+die2;//出题,输入结果,给出答案
if(die2>0)
t='+';
else
t='-';
cout<<"请运算"<<die1<<t<<die2<<'='<<endl;//列出公式
cout<<"请作答:"<<endl;
return worksum;
}
}
// Find.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
typedef istream_iterator<string> In_str;
In_str end;
//统计类
class Count
{
public:
Count(string const & f) :ob(f),line(0),count(0){}
void operator()(char const * second)
{
istringstream is(second);
In_str begin(is);
++line;
for(int x=1;begin!=end;++x,++begin)
{
if(ob==(*begin)) {++count;place.push_back(make_pair(x,line));}
}
}
void out()
{
cout<<"/n你想找的字符出现了"<<count<<"次。/n";
if(count)
{
cout<<"分别出现在以下位置:/n";
for(int i=0;i<count;i++)
{
cout<<"第"<<i+1<<"次在 第"<<place[i].second<<"行,第"<<place[i].first<<"个单词的位置出现/n";
}
}
}
private:
vector<pair<int,int> > place;
long count;
string ob;
long line;
};
//主程序
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"请输入文件名:";
std::ifstream fp((*In_str(cin)).c_str());
if(fp)
{
cout<<"/n输入你想找的字符:";
Count cn(*In_str(cin));