【问题标题】:Reverse characters of each words in vector string反转向量字符串中每个单词的字符
【发布时间】:2015-06-02 02:36:20
【问题描述】:
vector <string> theWords;
theWords.reserve(100);

istream_iterator <string> stringReader(cin);
istream_iterator <string> stringReaderEOF;

while(stringReader != stringReaderEOF)
    theWords.push_back(* stringReader++);

display(theWords);
//reverse(theWords);

输入:

萨明汗

输出:

萨明

倒车后:

尼玛

nahk

如何反转字符?

【问题讨论】:

  • 反向不保留。

标签: c++ string algorithm c++11 vector


【解决方案1】:

这段代码将反转vector&lt;string&gt;的所有字符串元素

#include <string> 
#include <algorithm>

void main()
{
    vector<string> a = { "abc", "pqr", "xyz" };
    for (auto& s : a)
    {
        reverse(begin(s), end(s));
    }
}

【讨论】:

  • @SaminKhan 它有效。添加使用命名空间标准。还包括矢量。
【解决方案2】:
void reverse(string& s)
{
    int i = 0, j = s.length() - 1;
    while(i < j)
    {
        swap(s[i++], s[j--]);
    }
    cout << s << endl;
}

在 main() 中:

reverse(theWords[0]);
reverse(theWords[1]);
//.....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2013-11-13
    • 2015-12-13
    相关资源
    最近更新 更多