nev*_*int 0 c++ unix string algorithm counting
我有以下排序数据:
AAA
AAA
TCG
TTT
TTT
TTT
Run Code Online (Sandbox Code Playgroud)
我想计算每个String的出现次数:
AAA 2
TCG 1
TTT 3
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用uniq -c,但在这里我需要对我拥有的整个C++代码进行额外的处理.
我坚持使用这个结构(根据'pgras'建议修改):
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string line;
ifstream myfile (arg_vec[1]);
if (myfile.is_open())
{
int count;
string lastTag = "";
while (getline(myfile,line) )
{
stringstream ss(line);
string Tag;
ss >> Tag; // read first column
//cout << Tag << endl;
if (Tag != lastTag) {
lastTag = Tag;
count = 0;
}
else {
count++;
}
cout << lastTag << " " << count << endl;
}
cout << lastTag << " " << count << endl;
myfile.close();
}
else {cout << "Unable to open file";}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它打印出错误的结果:
AAA 0
AAA 1
TCT 0
TTT 0
TTT 1
TTT 2
TTT 2
Run Code Online (Sandbox Code Playgroud)
如果你只想打印出来,你的算法就可以了.如果要将其传递给另一个函数,可以使用例如STL映射.
map<string, int> dict;
while(getline(myfile,line)) {
string Tag;
stringstream ss(line);
ss >> Tag;
if (dict.count(Tag) == 0)
dict[Tag] = 1;
else
dict[Tag]++;
}
Run Code Online (Sandbox Code Playgroud)