c++ - 在C++中将txt文件排序为 vector

标签 c++ sorting vector

大家好,我有一个 C++ 问题。

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

一旦我阅读了文件,我需要按照分配给它们的编号顺序将名称放在 vector 中。所以当我打印 vector 时,它应该按以下顺序:

妮可

山姆

汤姆

汤姆

汤姆

约翰

然后我需要获取排序后的 vector 并将名称放入一个新文件中,其中包含每个名称出现的次数。所以当我打印这个新文件时,输出应该是这样的:

妮可 1

山姆 1

简 2

汤姆 3

本 1

约翰 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

山姆

6

汤姆

1

妮可

5

汤姆

4

8

所以我需要帮助让它们按正确的顺序排列(名称按照它们前面的数字顺序排列)然后将它们写入新的 txt 文件 谢谢

最佳答案

你可以做一个 std::vector<std::pair<int, std::string>>只需使用 std::sort(<yourvec>.begin(), <yourvec>.end()对您的成员进行排序。 创建 std::pair<int, std::string> ,使用您的号码和与之关联的名称调用构造函数。

关于c++ - 在C++中将txt文件排序为 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19715815/

相关文章:

MySQL Limit 和 Order Left Join

python - 如何在模型方法字段(不是模型字段)上对 Django 管理列进行排序

python - 如何对字母数字 pandas 索引进行降序排序。

c++ - 如何在 vector 中的某个数字之后重新计算一个过程

c++ - 初学者 C++ 程序员,对动态数组感到困惑

c++ - 如何将宽字符串转换为 ASCII

c++ - 写入二进制文件时空格过多

c++ - unordered_map 在实践中真的比 map 快吗?

c++ - 在指针 vector 中释放内存的正确方法? (C++)

C++ 找不到兼容的标准构造函数