首页 > 解决方案 > 如何用单词排列向量中的每个字符?

问题描述

我想像这样安排每个单词:

输入

5
viguo
lkjhg
tyujb
asqwe
cvbfd

输出

aeqsw
bcdfv
bjtuy
ghjkl
giouv

我想从你那里得到一些想法。谢谢!

标签: c++stringsortingvectorc++14

解决方案


您需要应用该算法std::sort两次。

第一个用于向量的每个元素,第二个用于向量本身。

这是一个演示程序。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector<std::string> v =
    {
        "viguo", "lkjhg", "tyujb", "asqwe", "cvbfd"
    };

    for ( const auto &s : v ) std::cout << s << ' ';
    std::cout << '\n';

    for ( auto &s : v ) std::sort( std::begin( s ), std::end( s ) );

    std::sort( std::begin( v ), std::end( v ) );

    for ( const auto &s : v ) std::cout << s << ' ';
    std::cout << '\n';

    return 0;
}

它的输出是

viguo lkjhg tyujb asqwe cvbfd 
aeqsw bcdfv bjtuy ghjkl giouv 

推荐阅读