【发布时间】:2020-01-22 18:04:11
【问题描述】:
尝试使用 C++ 结构解决问题。对句子中每个单词的引用被取反。但是在原句中没有看到变化。
class Solution {
public:
string reverseWords(string s) {
istringstream ss(s);
for(auto w = istream_iterator<string>(ss); w != istream_iterator<string>(); w++)
{
/* changes of the below 2 lines are not reflected in the main sentence*/
string &str = const_cast<string&>(*w);
reverse(str.begin(),str.end());
}
reverse(s.begin(),s.end());
return s;
}
};
【问题讨论】:
-
以这种方式使用
const_cast是未定义的行为。仅此一项就使整个程序出错。仅仅因为你告诉编译器忽略常量,并不意味着常量不存在。 -
@DeiDei:如何在不复制单词的情况下完成工作。
-
不值得。只需将句子拆分为单词并将它们添加到
std::vector,然后只需return std::string(vector.rbegin(), vector.rend());。你完成了。只需 2-3 行代码即可完成。
标签: c++ c++11 istringstream