选出对称串并按长度排列输出,请问要怎么才能按长度排列输出?可以的话麻烦说一下详细易懂解题思路
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <ranges>
using namespace std;
bool symmetric(const string &s)
{
if (s.empty())
return true;
auto p = s.begin();
auto q = --s.end();
while (p < q)
{
if (*p != *q)
return false;
++p;
--q;
}
return true;
}
int main()
{
vector<string> strs;
for (const auto &s : ranges::subrange(istream_iterator<string>(cin), istream_iterator<string>()) | ranges::views::filter(symmetric))
strs.push_back(s);
sort(strs.begin(), strs.end(), [](const auto &lhs, const auto &rhs)
{ return lhs.length() < rhs.length(); });
copy(strs.begin(), strs.end(), ostream_iterator<string>(cout, "\n"));
return 0;
}
$ g++ -Wall -std=c++20 main.cpp
$ ./a.out
123321
123454321
123
312
sdfsdfd
121212
\\dd\\
123321
\\dd\\
123454321
先找出对称字符串,现在找到对称字符串
例如
121 长度3
asdfdsa 长度7
12321 长度5
然后把他们按长度排序输出就好了、
121 长度3
12321 长度5
asdfdsa 长度7