【问题标题】:reverse words in a sentence using istringstream and istream_iterator使用 istringstream 和 istream_iterator 反转句子中的单词
【发布时间】: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


【解决方案1】:

我认为在不复制单词的情况下使用流是不可能的,因为流总是会将单词提取到单独的字符串中。在您的尝试中,您也在修改这样的副本,这就是您返回原始字符串的原因。我只会使用迭代器(这将被视为伪代码,可能无法编译):

auto last = s.begin();
auto cur = s.begin();

while (cur != s.end()) {
  if (!isalpha(*(cur++))) {
     reverse(last, cur);
     last = cur;
  }
}

reverse(last, cur);
return s;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多