使用istringstream和istream_迭代器反转句子中的单词 试图用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; } }; 类解决方案{ 公众: 字符串反转符(字符串s){ istringstream ss(s); for(auto w=istream_迭代器(ss);w!=istream_迭代器();w++) { /*以下两行的变化未反映在主句中*/ 字符串&str=const_cast(*w); 反向(str.begin(),str.end()); } 反向(s.开始(),s.结束()); 返回s; } };

使用istringstream和istream_迭代器反转句子中的单词 试图用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; } }; 类解决方案{ 公众: 字符串反转符(字符串s){ istringstream ss(s); for(auto w=istream_迭代器(ss);w!=istream_迭代器();w++) { /*以下两行的变化未反映在主句中*/ 字符串&str=const_cast(*w); 反向(str.begin(),str.end()); } 反向(s.开始(),s.结束()); 返回s; } };,c++,c++11,istringstream,C++,C++11,Istringstream,我不认为不复制单词就可以使用流,因为流总是将单词提取到单独的字符串中。在您的尝试中,您还修改了这样一个副本,这就是返回原始字符串的原因。我将只使用迭代器(这将被视为伪代码,可能无法编译): 以这种方式使用const\u cast是未定义的行为。单凭这一点,整个程序就错了。仅仅因为你告诉编译器忽略constness,并不意味着constness不在那里。@DeiDei:我如何在不复制单词的情况下完成工作。这不值得。只需将句子拆分成单词并将它们添加到std::vector,然后只需返回std::st

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


以这种方式使用
const\u cast
是未定义的行为。单凭这一点,整个程序就错了。仅仅因为你告诉编译器忽略constness,并不意味着constness不在那里。@DeiDei:我如何在不复制单词的情况下完成工作。这不值得。只需将句子拆分成单词并将它们添加到
std::vector
,然后只需
返回std::string(vector.rbegin(),vector.rend())。你完成了。可以用2-3行代码完成。
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;