如何检查C ++ STL列表是否为回文?
how to check whether c++ STL list is palindromic or not?
我想检查给定的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 的意思是"相同的向前和向后读取",因此只需将c
与std::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
使用基本测试用例进行演示
相关文章:
- 在STL - C++中按成绩对学生列表进行排序?
- 使用列表 STL 递归进行插入排序
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- 如何检查C ++ STL列表是否为回文?
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- C++ 在列表末尾插入元素的列表的 STL 向量
- 清除 C++ 中的指针的 STL 列表
- 在列表中找到最常见的元素(C STL)
- 在Visual Studio 2013中编译的STL列表代码在Visual Studio 2019中给出了错误.想知道原
- 列表STL的时间复杂性在一段时间内进行排序
- 使用.txt文件填充 STL 列表不起作用
- 在 stl 映射和列表 (c++) 上进行迭代的泛型循环
- 为 STL 列表编写选择排序
- STL C 中不同类型的列表声明的错误
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 如何从 STL 列表中删除结构记录
- C++如何将 STL 列表传递给函数
- 漂亮的打印不适用于C ++ STL列表
- 使用列表 STL 时出错
- 如何将列表 STL 的迭代器转换为实例 (C++)