C++ 检查字符串流中的重复项
字符串流是一个给定数据的连续流,其中流的每个元素表示一个字符串。该流允许对字符串数据进行大规模处理。在C++中,我们有一些基于STL(标准模板库)的函数,比如count()和insert(),可以检查字符串流中的重复项。
使用标准模板库
该程序使用C++的STL,设置了头文件unordered,表示唯一关键元素,并帮助解决字符串流中的重复项。
语法
以下是示例中使用的语法-
static unordered_set<data_type> unq_string;
unq_string是一种静态数据类型变量的声明,意味着一旦声明,变量和成员函数就不能被修改。unordered_set是一种容器数据结构,该结构只能存放唯一的元素。
count()
count() 是C++ STL中的预定义函数,用于返回给定数组字符串中元素的出现次数。
insert()
insert()是C++ STL的另一个预定义函数,可以在特定元素之前添加元素。
步骤
以下步骤为-
步骤1:通过指定必要的头文件(如iostream、unordered_set和string),启动程序。
步骤2:然后使用函数定义check_dup_element(),该函数接受参数s,类型为const string&,处理字符串重复操作。
步骤3:初始化容器数据结构“static unordered_set
步骤4:接下来,使用if语句根据给定字符串(即变量s)中的重复字符串设置条件。如果找到重复字符串,它将打印语句“找到重复元素”,否则它将使用内置函数insert()与静态变量unq_string一起,只会添加字符串中存在的唯一元素,并打印语句“找到唯一元素”。
步骤5:现在启动主函数,并将数组元素存储在变量str中,类型为string。然后找到数组的大小并存储在变量n中。
步骤6:继续使用for循环,使用调用名为check_dup_element()的函数,该函数接受参数str[i],其中变量i迭代输入字符串并显示结果。
示例
在以下示例中,我们将使用静态变量
#include <iostream>
#include <unordered_set>
#include <string>
using namespace std;
void check_dup_element(const string& s)
{
static unordered_set<string> unq_string;
// Check if the string is already present in the set
if (unq_string.count(s) > 0)
{
cout << "The repeated element found" << endl;
}
else
{
unq_string.insert(s);
cout << "The unique element found" << endl;
}
}
// Start the main function
int main() {
string str[] = {"A", "B", "C", "C","A","D"};
// Find the size of an array
int n = sizeof(str) / sizeof(str[0]);
// Iteration of each element from the string
for (int i = 0; i < n; i++) {
check_dup_element(str[i]);
}
return 0;
}
输出
The unique element found
The unique element found
The unique element found
The repeated element found
The repeated element found
The unique element found
结论
我们探索了字符串流重复复制的概念,以从给定的字符串数组中找到重复的元素。该程序使用了一些预先存在的内置函数,如count()和insert(),分别用于确定元素出现的次数和插入。它有多种应用,如数据处理,自然语言处理,日志分析等。