2016-07-05 22 views
-1

我正在设计一个游戏WordBrain的作弊。基本上这只是一个小程序,需要一些字母,将序列置换,然后将序列分成具有长度属性的“单词”,然后搜索我的文本文件以提交有意义的排列以便打印出来。(C++)不能使用string :: substr将子字符串分配给对象

while (next_permutation(letters.begin(), letters.end())) //loop through possible permutations of the combination 
    { 
     int position_marker = 0; //serve specific purpose 
     for (auto x : substring_collection) //trouble is in this loop 
     { 
      string temp; 
      int k = x.take_length(); 
      try { temp = letters.substr(position_marker, k); } 
      catch (out_of_range) { cout << "OUT OF RANGE"; } 
      x.set(temp); //member content does not register change 
      position_marker += x.take_length(); //also member word_length is 0 now, despite their are no invocation of methods capable of changing it 
     } 
     if (all_of(substring_collection.begin(), substring_collection.end(), [&](substring & s) {return !(library.find(s.take_content()) == library.end()); })) 
     { 
      for (auto x : substring_collection) 
      { 
       cout << x.take_content() + " "; 
      } 
     } 
    } 

这是麻烦来自的位置。基本上,substring_collection是vector<substring>,其中包含的类的对象substring 这里是一流的样子:

class substring 
{ 
private: 
    std::string content; 
    int word_length; 
public: 
    substring() : content(""), word_length(0) {}; 
    substring(std::string & s, int c) : content(s), word_length(c) {}; 
    void set(std::string & s) 
    { 
     content = s; 
    } 
    void clear() 
    { 
     content.clear(); 
    } 
    void set_length(int c) 
    { 
     word_length = c; 
    } 
    void showinfo() const 
    { 
     std::cout << "Content is " + content << " Length is : " << word_length; 
    } 
    int take_length() const 
    { 
     return word_length; 
    } 
    std::string take_content() const 
    { 
     return content; 
    } 
}; 

我怀疑代码出错的原因是position_marker,其价值取决于该成员word_length“的对象substring设置为0. 在此循环之前的代码中,我只是该成员从用户输入(从std::cin)获取数据的设置方法。 你能告诉我,是否有任何隐藏的机制重置财产,或创建我不知道的品牌新对象? 此外,编码风格的教学非常受欢迎。我刚开始学习编码,因此非常感谢任何提示。

+0

您应该包括为什么您认为它在提到的行上失败,以及它如何不按预期工作/运行的描述。 –

+0

谢谢你的提示。我将确保包括如果在未来出现其他问题时,错误如何出现。目前,我已经制定出解决方案。 – StormBlade

回答

0
for (auto x : substring_collection) 

这里,xsubstring类型。这是向量中元素的副本,然后当您修改它时,您只修改副本,而不是原始副本。

你必须使用引用来修改原始元素的矢量

for (auto& x : substring_collection) 

为什么word_length0,我不知道,这是不是在你的代码发布。我的猜测是你resized这个向量,它被称为substring的默认构造函数,它将word_length设置为0

+0

谢谢。你救了我的命。事实证明,这正是你确定的!代码在子字符串的副本上执行,而不是原始代码,因此当我尝试从cin读入输入时,原始代码不受影响。我试图使用参考,现在它的工作! – StormBlade