c++ - 独立的事物相互影响(我不知道发生了什么)

标签 c++ vector fstream

对不起标题,但我真的不知道问题出在哪里。代码看起来是这样的(这里没有任何意义,但是在更大的项目中是有的,所以请不要问“你为什么要这样做......”)

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

string sort (string slowo){
  string litery = slowo;

  for (int i=0; i<litery.length()-1; i++)
     for (int j=0; j<litery.length()-1; j++)
        if (litery[j]>litery[j+1])
             swap(litery[j], litery[j+1]); // (3)

  return litery;
}

int main()
{

    fstream wordlist;
    wordlist.open("wordlist_test",ios::in);
    vector<string> words;

    while (!wordlist.eof()){ // (4)
      bool ok = true;
      string word;
      getline(wordlist,word);
      string sorted = sort(word);

      if (ok){
        cout<<word<<endl; // (1)
        words.push_back(word);
     }
  }

  for (int i = 0; i<words.size(); i++){
    cout<<words[i]<<endl; // (2)
  }

}

文件“wordlist_tests”中有单词。最后的程序应该只将它们写入 vector 并将 vector 中的内容写入标准输出。问题是:

  • 然而第(1)行证明所有的词都可以
  • 载体似乎是 第(2)行为空

现在很有趣(可能只适合我)部分:

有两种方法可以使它正确:

  • 我可以删除第(3)行(但是,如果我是对的,当变量通过值传递给排序函数时,它只是交换自变量中的两个字母;它与我的 vector 无关),或者:
  • 我可以在 while 循环 (4) 中更改条件。

例如像这样:

int tmp = 0;
while (tmp < 5){
tmp++;
/..../

这段代码有什么问题?我应该如何将这些词写成 vector 但仍然对它们进行排序并使用这个 while 循环?我找不到这些东西之间的联系(好的,我看到联系是可变词,但我不知道是什么方式)。任何帮助表示赞赏。

最佳答案

如果其中一个单词是空字符串 ""swap() 会发生什么?

  1. 如果发生这种情况,litery = ""
  2. 循环中的条件将从 0 迭代到 (unsigned) 0 - 1,这是一个非常大的数字。
  3. 然后您将执行 if (litery[0] > litery[1])
  4. litery[1] 将访问超出空字符串末尾的部分,这会导致未定义的行为。

让我们解决这个问题:

对此的常见修复是从 1 迭代到 string.length()。这是一个例子:

string sort (string litery){
    for (int i=1; i<litery.length(); i++)
        for (int j=1; j<litery.length(); j++)
            if (litery[j-1]>litery[j])
                swap(litery[j-1], litery[j]); 

    return litery;
}

关于c++ - 独立的事物相互影响(我不知道发生了什么),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28141233/

相关文章:

java - 无法在 JNI 中调用 ctor?

c++ - 将 std::find_if() 与采用多个输入参数的比较函数一起使用

python - 如何计算满足给定条件的向量的所有排列

c++ - 为什么我的 fstream 没有创建 data1.txt 文件?

c++ - 同时文件流是否有限制?

C++/fstream : cannot create a new file

c++ - std::unordered_set::erase 复杂度

c++ - 在构造函数中指向 this 的弱指针

c++ - 在 C++ 中,如何在不通过参数传递对象的情况下重载运算符?

vector - 使用 RcppParallel 进行向量的并行加法