[英]sorting txt file into a vector in c++
hey guys i have a c++ question. 嗨,我有一个C ++问题。
im trying to write a program that will open and read a txt file of numbers and names such as: "9 john 3 jane 7 tom 2 sam 6 tom 1 nicole 5 tom 4 jane 8 ben" 我试图编写一个程序,该程序将打开并读取数字和名称为txt的文件,例如:“ 9约翰3简7汤姆2萨姆6汤姆1妮可5汤姆4詹8本”
once ive read the file i need to place the names in a vector in order of the numbers assigned to them. 一旦我读了文件,我需要按照分配给它们的数字的顺序将名称放置在向量中。 so when i print the vector it should be in this order:
所以当我打印矢量时,它应该是这样的:
nicole 妮可
sam SAM
jane 简
jane 简
tom 汤姆
tom 汤姆
tom 汤姆
ben 本
john 约翰
then i need to take the sorted vector and place the names in a new file with the number of times each name occurs. 然后我需要采取排序的向量,并将名称与每个名称出现的次数一起放入新文件中。 so when i print this new file the output should look like this:
因此,当我打印此新文件时,输出应如下所示:
nicole 1 妮可1
sam 1 山姆1
jane 2 简2
tom 3 汤姆3
ben 1 本1
john 1 约翰一书
so far this is my code: (ignore the count_names function as i was only using it to test my output) (i will need to do a recursive function later on so ignore any #include that i do not need at the moment) 到目前为止,这是我的代码:(忽略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;
}
so as of right now this is my output: 所以到目前为止,这是我的输出:
9 9
john 约翰
3 3
jane 简
7 7
tom 汤姆
2 2
sam SAM
6 6
tom 汤姆
1 1个
nicole 妮可
5 五
tom 汤姆
4 4
jane 简
8 8
ben 本
so i need help getting them into the proper order (the names in order of the number before them) and then writing them to the new txt file thanks 所以我需要帮助将它们按正确的顺序排列(名称按它们之前的编号顺序排列),然后将它们写入新的txt文件中,谢谢
您可以执行std::vector<std::pair<int, std::string>>
并仅使用std::sort(<yourvec>.begin(), <yourvec>.end()
对您的成员进行排序。要创建一个std::pair<int, std::string>
,请使用您的数字以及与之链接的名称来调用构造函数。
If the numbers are unique, put the numbers and names into a std::map<int, std::string>
. 如果数字是唯一的,请将数字和名称放入
std::map<int, std::string>
。 While you are at it, count the occurrences of each name in a std::map<std::string, unsigned int>
. 在使用它时,请在
std::map<std::string, unsigned int>
计算每个名称的出现次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.