【问题标题】:I have a question about 'push_back()' with reverse_iterator我对带有 reverse_iterator 的“push_back()”有疑问
【发布时间】:2021-03-15 14:31:06
【问题描述】:
#include<string>
#include<iterator>
#include<vector>
#include<iostream>

int main(){

    std::string str = "abc";
    std::string str2 = str;
    std::vector<int>::reverse_iterator rit = str.rbegin();
    for(rit+1; rit != str.rend(); rit++){
        str2.push_back('*rit');
    }
    std::cout << str2 << std::endl;
}

我预计输出是“abcba”,但 push_back() 中似乎有错误。谁来帮帮我T_T

【问题讨论】:

  • 你需要告诉我们你遇到了什么错误,你知道的。
  • str2.push_back('*rit'); -> str2.push_back(*rit); 对于初学者。
  • @ee amil 在 C 中没有反向迭代器。
  • @AKX 多字符字符常量 [-Wmultichar] 隐式常量转换溢出 [-Woverflow]
  • @VladfromMoscow 对不起!!它是 C++

标签: c++ string iterator reverse-iterator


【解决方案1】:

对于初学者有一个错字(或者你想突出显示)

str2.push_back('*rit');

看来你的意思

str2.push_back( *rit);

此声明

std::vector<int>::reverse_iterator rit = str.rbegin();

没有意义。声明的对象和用作初始化器的正确表达式具有不同的类型,并且它们之间没有隐式转换。

您需要的是以下内容

    std::string str = "abc";
    std::string str2 = str;

    str2.append( str.rbegin(), str.rend() );

    std::cout << str2 << '\n';

或者你可以写

    std::string str = "abc";
    std::string str2 = str;

    for (std::string::reverse_iterator it = str.rbegin(); it != str.rend(); ++it)
    {
        str2.push_back( *it );
    }

    std::cout << str2 << '\n';

或者for循环可以写成这样

for (auto it = str.rbegin(); it != str.rend(); ++it)

【讨论】:

  • 天哪,问题解决了。非常感谢你的帮助!!!!!! ★★★★★★★
  • @eeamil 如果问题得到解决,您可以选择最佳答案关闭问题。
猜你喜欢
  • 1970-01-01
  • 2020-12-30
  • 2017-02-22
  • 2019-05-06
  • 1970-01-01
  • 2020-10-17
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多