C++ 根据输入文本的重复次数对其进行排序?
我正在尝试制作一个程序,从用户那里读取输入文本,然后打印出每个单词,以及按照排序顺序重复了多少次。(输入用空格分隔,可以包含标点符号,但不能包含新行) 输入示例:我是一名优秀的程序员,我喜欢C语言 输出应为:C++ 根据输入文本的重复次数对其进行排序?,c++,class,sorting,vector,C++,Class,Sorting,Vector,我正在尝试制作一个程序,从用户那里读取输入文本,然后打印出每个单词,以及按照排序顺序重复了多少次。(输入用空格分隔,可以包含标点符号,但不能包含新行) 输入示例:我是一名优秀的程序员,我喜欢C语言 输出应为: a:2次 I:1次 上午:1次 好:1次 。。。等等 **对于输入,我使用了向量和类,但我不知道为什么我不能在其中推送几个项 class word {public: word(); void set_data(string data_value); void printing_data
- a:2次
I:1次
上午:1次
好:1次 。。。等等
class word {public:
word();
void set_data(string data_value);
void printing_data();
void counter_addition();
int count;
string data;};
int main(){/*创建列表类类型的vecotr调用项*/
向量项;
/*创建列表类类型的变量,用于将数据推送到向量中*/
单词*元素;
/*读取由空格分隔的输入文本*/
int size=0;
字符串文本;
cout存储字符串值并计数到std::map中,对于每个单词,检查它是否已经在映射中。如果它已经在映射中,则增加计数。在相反的情况下,使用count=1插入它。存储字符串值并计数到std::map中,对于每个单词,检查它是否已经在映射中。如果它是re,增加计数。在相反的情况下,使用count=1插入它,基本上,迭代每个单词(2个循环)并使用(strcmp)比较单词和增量计数器。也包括结构,因为它将使任务更容易存储字符串并在结构中重复,而不是每次都生成新变量。另外,由于您是编程新手,所以不要以效率为目标,而是以正确的代码为目标。因此,将用户输入存储在文件中,因为它比使用子字符串更容易处理基本上是迭代在每个单词上(2个用于循环)并使用(strcmp)比较单词和增量计数器。也包括结构,因为它将使任务更容易存储字符串并在结构中重复,而不是每次都生成新变量。另外,由于您是编程新手,所以不要以效率为目标,而是以正确的代码为目标。因此,将用户输入存储在文件中,因为它比使用子字符串更容易处理
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;
}