如何检查C ++ STL列表是否为回文?

how to check whether c++ STL list is palindromic or not?

本文关键字:列表 STL 是否 回文 何检查 检查      更新时间:2023-10-16

我想检查给定的C++ STL 列表是否为回文?

bool isPalindromic(list <int> c);
int main(){
list<int> l;
l.push_front(12);
l.push_front(35);
l.push_front(34);
l.push_front(35);
l.push_front(12);
isPalindromic(l);
}
output : true 

您可以使用std::equal来检查开头的列表是否等于结尾的列表。 std::equal的cppReference页面甚至有一个示例。

编辑(根据要求(: 基于 cpp 首选项提供的示例:

std::equal(s.begin(), s.begin() + s.size()/2, s.rbegin());

上面的行检查字符串是否为回文。但是在我们的例子中它不起作用,因为 list 的begin()返回BidirectionalIterator,而不是RandomAccessIterator字符串的begin()返回,所以我们不能做s.begin() + s.size()/2部分。要使其正常工作,我们应该将代码更改为:

bool is_palindrome(const std::list<int>& l) //use templated version std::list<T> if needed
{
return std::equal(l.begin(), l.end(), l.rbegin());
}

这当然并不完美,因为它从列表的开头到结尾迭代,而它可能只是在中间之后结束,但它很简单而且有效。

Palindrome 的意思是"相同的向前和向后读取",因此只需将cstd::reverse(c)进行比较即可。

简单的解决方案,避免了std::equal(begin, end, rbegin)执行的不必要的比较:

template<typename T>
bool is_palindrome(const std::list<T>& list) {
auto it1 = list.begin();
auto it2 = list.end();
if (list.size() % 2 == 0) {
while (it1 != it2)
if (!(*it1++ == *--it2))
return false;
} else {
while (it1 != --it2)
if (!(*it1++ == *it2))
return false;
}
return true;
}

请注意,自 C++11 以来,std::list::size具有恒定的时间复杂度。

例:

std::list<int> l{12, 35, 34, 35, 12};
std::cout << std::boolalpha << is_palindrome(l);   // Output: true

使用基本测试用例进行演示