我有一个关于 'push_back()' 和 reverse_iterator 的问题
I have a question about 'push_back()' with reverse_iterator
#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);
这个声明
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)
#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);
这个声明
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)