首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在c++中将txt文件排序为向量

在c++中将txt文件排序为向量
EN

Stack Overflow用户
提问于 2013-10-31 20:15:39
回答 2查看 1.4K关注 0票数 0

嘿,伙计们,我有个c++问题。

我试图编写一个程序来打开和读取一个txt文件中的数字和名字,例如:"9 john 3 jane 7 tom 2 sam 6 tom nicole 5 tom 4 jane 8 ben“

一旦我读取了这个文件,我就需要按照分配给他们的数字的顺序,把名字放在向量中。所以当我打印向量时,它应该是这样的:

妮可

相同的

汤姆

汤姆

汤姆

约翰

然后,我需要得到排序的向量,并将名称放在一个新文件中,其中包含每个名称出现的次数。因此,当我打印这个新文件时,输出应该如下所示:

妮可1

萨姆1

简2

汤姆3

本1

约翰1

到目前为止,这是我的代码:(忽略count_names函数,因为我只是使用它来测试我的输出)(稍后我需要执行一个递归函数,所以忽略我目前不需要的任何#include )

代码语言:javascript
复制
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

相同的

6

汤姆

1

妮可

5

汤姆

4.

8

因此,我需要帮助他们进入正确的顺序(按前面数字的顺序排列),然后将它们写到新的txt文件中,谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-31 15:38:37

您可以执行std::vector<std::pair<int, std::string>>,只需使用std::sort(<yourvec>.begin(), <yourvec>.end()对成员进行排序。要创建一个std::pair<int, std::string>,请使用您的编号调用构造函数,并使用它链接的名称。

票数 1
EN

Stack Overflow用户

发布于 2013-10-31 20:24:51

如果数字是唯一的,则将数字和名称放入std::map中。在此期间,请计算std::map中每个名称的出现情况。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19715815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档