简体   繁体   English

使用迭代器反转字符串

[英]Reversing a String Using Iterators

I'm trying to reverse a string (eg change "bro" to "orb") using iterators.我正在尝试使用迭代器反转字符串(例如将“bro”更改为“orb”)。 Unfortunately, my code doesn't work.不幸的是,我的代码不起作用。 Here's my code:这是我的代码:


for(std::string text; std::cin >> text;){
    for(std::string::const_iterator it = text.cend() + 1; it <= text.cbegin(); --it)
        std::cout << *it;
}


return 0;}

Where did I go wrong?我在哪里 go 错了?

Firstly your code isn't reversing a string, it's printing a string backwards.首先,您的代码不是反转字符串,而是向后打印字符串。 Not the same thing at all.根本不是一回事。

The easy way to print a string backwards would be to use a reverse iterator向后打印字符串的简单方法是使用反向迭代器

for (auto it = text.rbegin(); it != text.rend(); ++it)
    std::cout << *it;

But if you want to do it with a regular iterator then the following works但是如果你想用一个常规的迭代器来做,那么下面的工作

auto it = text.end();
while (it > text.begin())
     std::cout << *--it;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM