【问题标题】:Comparing strings by using two different queues使用两个不同的队列比较字符串
【发布时间】:2015-05-08 20:47:46
【问题描述】:

刚开始使用队列,需要朝着正确的方向推进。

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

我尝试了一些方法无济于事。我无法理解我应该做什么才能以可以比较两者的方式访问字符串中的字符。

#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?
}

【问题讨论】:

  • pop_front 是队列的出队操作。这是否为您指明了正确的方向?
  • 这个问题通常不清楚,但我认为这意味着您需要在每个队列中一次一个字母地阅读句子。所以你真的需要std::queue&lt;char&gt; q;
  • 只有 1 个项目的队列似乎有点愚蠢。你确定你不应该在其中存储单个字符吗?然后只是弹出字符直到结束或不匹配。
  • 是的,您的教授很可能希望您逐字比较。

标签: c++ string queue deque


【解决方案1】:

我认为你必须使用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    相关资源
    最近更新 更多