在不知道输入大小的情况下对字符串 c++ 向量进行排序

Sorting a vector of strings c++ without knowing the size of the input

本文关键字:c++ 字符串 向量 排序 情况下 输入 不知道      更新时间:2023-10-16

我在对字符串向量进行排序时遇到问题。我不应该询问字符串的数量(向量的大小),输入应该只包括应该排序的字符串。为了找到向量的大小以便对其进行排序,我尝试了这种方法,但它不起作用:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool sortfunc(string i , string j)
{
    return (i < j);
}

int main()
{
    vector<string>s;
    string str;
    int count = 0;
    do
    {
        cin >> str;
        s.push_back(str);
        count++;
    }
    while (str);
    sort(s.begin(), s.begin() + count, sortfunc);
    for (int i = 0; i < count; i++)
        cout << s[i] << endl;
}

您的循环条件没有任何意义。 str不能转换为布尔值。相反,您应该像这样构建它:

while (cin >> str)
{
    s.push_back(str);
    count++;
}

否则,您的代码工作正常。如果要避免保留计数器变量,可以使用s.end()而不是s.begin() + count。最后,您不需要提供自定义比较器,默认情况下它已经使用operator<

sort(s.begin(), s.end());