迭代器通过许多不同类型的队列

时间:2017-09-02 14:38:39

标签: c++ templates

我有许多队列,他们总是成对出现。像队列A& B,队列C& D等等

队列的类型不同,但来自一个模板类。喜欢

promptInt :: IO Int
promptInt = do
  putStr "Int: "
  line <- getLine
  case readMaybe line of
    Just x -> return x
    _      -> putStrLn "Try again." >> promptInt

promptChar :: IO Char
promptChar = do
  putStr "Char: "
  line <- getLine
  case line of
    [x,_] -> return x
    _     -> putStrLn "Try again." >> promptChar

我的目标是比较a和b(然后是c和d,然后......),看看它们是否相同。我当然可以为不同的对进行3次while循环。但有没有任何聪明的方法,以防他们会像这样的许多队列。

1 个答案:

答案 0 :(得分:1)

你可以编写模板化函数,它需要你明确指定的两种类型的deques,所以你可以比较你想要的任何元素。

template<typename T, typename Container = std::deque<T>>
bool CompareQueues(Container& first, Container& second)
{
    if (first.size() != second.size())
    {
         return false;
    }

    for (auto it1 = first.begin(),
              it2 = second.begin();
         it1 != first.end() &&
         it2 != second.end();
         it1++, it2++)
    {
        if (*it1 != *it2)  // Overload operator '!=' in 'myqueueType', or compare them as you wish
        {
            return false;
        }
    }
    return true;
}

函数调用(对于整数):

std::deque<myqueueType<int> > a;
std::deque<myqueueType<int> > b;
CompareQueues<int>(a, b);

<强> See it live here.

相关问题