我试图编写一个程序,打开并读取数字和名称的txt文件,例如: “9 john 3 jane 7 tom 2 sam 6 tom 1 nicole 5 tom 4 jane 8 ben”
一旦我读取文件,我需要按照分配给它们的数字的顺序将名称放在向量中。因此,当我打印矢量时,它应按此顺序:
妮可
SAM
简
简
汤姆
汤姆
汤姆
贲
约翰
然后我需要获取已排序的向量并将名称放在一个新文件中,其中包含每个名称的出现次数。所以当我打印这个新文件时,输出应该如下所示:
妮可1
sam 1
jane 2
汤姆3
ben 1
john 1
到目前为止这是我的代码: (忽略count_names函数,因为我只用它来测试我的输出) (我稍后需要做一个递归函数,所以忽略我目前不需要的任何#include)
using namespace std;
void fill_vector ( vector<string> &v );
void print_vector ( vector<string> v );
int count_names ( vector<string> v );
int main()
{
vector<string> v;
string s;
fill_vector(v);
int num_names;
num_strings = count_strings(v)/2;
cout << "number of names " << num_names << endl;
print_vector(v);
return 0;
}
void fill_vector ( vector<string> &v )
{
string s;
ifstream fin;
string input = "toy_names.txt";
fin.open ( input.c_str() );
fin >> s;
while ( !fin.eof() )
{
v.push_back ( s );
fin >> s;
}
}
void print_vector ( vector<string> v )
{
for ( int i = 0; i < v.size(); i++ )
cout << v[i] << endl;
}
int count_names ( vector<string> v )
{
int counter = 0;
for ( int i = 0; i < v.size(); i++ )
{
counter++;
}
return counter;
}
现在这是我的输出:
9
约翰
3
简
7
汤姆
2
SAM
6
汤姆
1
尼科尔
5
汤姆
4
简
8
贲
所以我需要帮助让他们进入正确的顺序(按照他们之前的数字的顺序),然后将它们写入新的txt文件 谢谢
答案 0 :(得分:1)
您可以执行std::vector<std::pair<int, std::string>>
,只需使用std::sort(<yourvec>.begin(), <yourvec>.end()
对您的成员进行排序。
要创建std::pair<int, std::string>
,请使用您的编号和与之关联的名称调用构造函数。
答案 1 :(得分:0)
如果数字是唯一的,请将数字和名称放入std::map<int, std::string>
。在您使用它时,请计算std::map<std::string, unsigned int>
中每个名称的出现次数。