通过使用两个不同的队列比较字符串

Comparing strings by using two different queues

本文关键字:队列 字符串 比较 两个      更新时间:2023-10-16

刚开始使用队列工作,需要向正确的方向推动。

"编写一个读取两个句子并将其读为两个单独的队列的程序。然后,程序应通过比较两者之间的字符来确定句子是否相同。当遇到两个非相同字符时,该程序应显示一个消息表明句子不相同。

我尝试了一些事情,但无济于事。我很难理解我应该做的事情以从字符串中访问字符,以使我可以比较两者。

#include <iostream>
#include <string>
#include <deque>
using namespace std;
int main()
{
    deque<string> str1, str2;
    string s;
    cout << "Enter string #1: ";
    cin >> s;
    str1.push_back(s);
    cout << "Enter string #2: ";
    cin >> s;
    str2.push_back(s);
    // both queues have their respective strings. what now?
}

我认为您必须使用std::queue而不是std::deque

该程序看起来像

#include <iostream>
#include <queue>
#include <string>
int main()
{
    std::string s1;
    std::cout << "Enter sentence #1: ";
    std::getline( std::cin, s1 );
    std::string s2;
    std::cout << "Enter sentence #2: ";
    std::getline( std::cin, s2 );
    std::queue<char> q1;
    for ( char c : s1 ) q1.push( c );
    std::queue<char> q2;
    for ( char c : s2 ) q2.push( c );
    while ( !q1.empty() && !q2.empty() && q1.front() == q2.front() )
    {
        q1.pop();
        q2.pop();
    }
    if ( q1.empty() && q2.empty() )
    {
        std::cout << "nThe two sentences are identical" << std::endl;
    }
    else
    {
        std::cout << "nThe two sentences differ" << std::endl;
    }
    return 0;
}