从输入文本中排序单词取决于重复的次数?

时间:2017-12-05 16:30:48

标签: c++ class sorting vector

我正在尝试创建一个程序,该程序从用户读取输入文本,然后打印出每个单词以及按排序顺序重复的次数。 (输入由空格分隔,它可以保存标点但没有新行)

输入示例:我是一名优秀的程序员,我喜欢C语言

输出应该是:

  • a:2次
                       我:1次
                     上午:1次
                     好:1次

    ......等等。

**输入我使用了矢量和类,但我不知道为什么我不能在其中推送几个项目。

int main(){ /*creating vecotr called items of list class type*/
vector<word>items;

/*creating a variable of list class type which is used to push data into the vector*/

word *element;

/*Reading the input text seperated by white spaces*/
int size = 0;
string text;

cout << "Enter the text: " << endl;
getline(cin, text);

size = text.length();
int left_space = -1;
int right_space = 0;
string Sub_String;

/*main loop for constructing substring of words and then manipulating them*/

for (int i = 0; i<size; i++)
{

    /*splitting the string into words*/
    if (isspace(text[i]) || ispunct(text[i]))
    {
        right_space = i;

        Sub_String = text.substr(left_space + 1, right_space - left_space - 1);
        /*for first word just push it*/

        if (left_space == -1)
        {
            element = new word();
            element->set_data(Sub_String);
            items.push_back(*element);

        }

        else
        {
            /*compare to vector's data */
            for (int j = 0; j < items.size(); j++)
            {
                if (Sub_String == items[j].data)
                {
                    items[j].count = items[j].count + 1;
                }
                else
                {
                    element = new word();
                    element->set_data(Sub_String);
                    items.push_back(*element);
                }

            }
        }
            left_space = right_space;
    }
jfrog rt s https://URL/artifactory/generic-sgca/

如果单词相同则输出正确。

  

输入:生命生活

  

输出:生命重复:4

请帮我解决这个问题。我是编程新手。

1 个答案:

答案 0 :(得分:2)

将字符串值存储并计入std :: map&lt; std :: string,int&gt;并为每个单词检查它是否已经在地图中。如果它在那里,增加计数。在相反的情况下,插入count = 1