字串流中檢查重複項
字串流是給定資料的順序流,其中流的單個元素表示一個字串。該流允許處理大量字串資料。在 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(),它接受型別為 const string& 的引數 s 以對字串重複操作進行處理。
步驟 3:初始化容器資料結構“static unordered_set<data_type> unq_string;”,它處理程式碼的主要功能。
步驟 4:接下來,使用 if 語句,它根據給定字串(即變數 s)中重複的字串設定條件。如果找到重複的字串,它將列印語句“找到重複的元素”,否則它將使用內建函式 insert() 和靜態變數(即 unq_string),該函式僅新增字串中存在的唯一元素,並列印語句“找到唯一元素”。
步驟 5:現在啟動主函式並將陣列元素儲存在型別為 string 的變數 str 中。然後查詢陣列的大小並存儲在變數 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(),分別用於指定元素的出現次數和插入。它有多種應用,例如資料處理、自然語言處理、日誌分析等。
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP