从Vector中存储的字符串中只读取第一个字符

时间:2015-09-21 02:39:41

标签: c++ sorting

我目前正在编写一个编程作业,我应该从一致性中重新创建一段文本。我想首先根据线/节数对所有文本行进行排序。以下是样本一致性的样子(数字表示经文):

6 and I will *dwell in the house of
5 presence of my *enemies. You anoint my 
4 I will fear no *evil, for you are 
6 and love will *follow me all the days
6 Surely your *goodness and love will 
3 my soul. He *guides me along
5 You anoint my *head with oil; my cup 
1 shepherd, I *lack nothing.

使用下面的代码,我已将文件中的每一行读入矢量。

string inFileName;
ifstream conFile;
vector<string> conVec;
string info;

cout << "Welcome to the Concordance sorter!\n";
cout << "Please enter the file you would like to sort:\n\n";

cin >> inFileName;

conFile.open(inFileName.c_str());

if (conFile)
{

    while (!conFile.eof())
    {
        while (getline(conFile, info))
        {
            conVec.push_back(info);
        }   
    }

    conFile.close();
}

有没有办法让我只看字符串的第一个字符(诗句编号)然后用它来将矢量按数字顺序排序?我知道排序会如何发生,我只是不知道如何使用字符串中的第一个字符,或者甚至根本没有方法可以做到这一点。任何建议都会有很大的帮助!

2 个答案:

答案 0 :(得分:1)

我们不知道conVecinfo的类型,但conVec的元素类型是char*还是{{ 1}},std::string可以接收字符串的第一个字符。

答案 1 :(得分:0)

使用std::sort功能可以帮助您:

bool sortVector(char *a, char *b) {
   return *a < *b;
}

并将其称为

std::sort(conVec.start(), conVec.end(), sortVector);

这将适用于chars或std :: strings,只需将类型设置为正确。

相关问题