【问题标题】:What's wrong with my Vector stopping all of a sudden?我的 Vector 突然停止是怎么回事?
【发布时间】:2017-04-28 23:57:22
【问题描述】:

在它循环到元素 4096 后出现错误。由于某种原因,它停在那里并导致错误。有什么想法吗?

if(myFile.is_open()){

    while(getline(myFile, linePerLine) && cacheSizeVector.size() <= userInputCacheSize){

        cacheSizeVector.push_back(linePerLine);

        if (find(cacheSizeVector.begin(), cacheSizeVector.end(), linePerLine) != cacheSizeVector.end()){
            for(int i = 0; i <= userInputCacheSize; i++){
                if(cacheSizeVector[i] == linePerLine){    <<<<LINE OF ERROR!
                    lruCounter[i] = lruCounter[i] + 1;
                    cout << lruCounter[i] << endl;
                    cout << cacheSizeVector[i] << " HIT!" << endl;
                    cout << cacheSizeVector.size() << endl << endl;
                }
            }

        }
        else{
            std::cout << "Element not found in myvector\n";
        }

一些初始化的错误:

"{返回 __is_long() ? __get_long_size() : __get_short_size();}"

【问题讨论】:

  • 首先要做的事情:您是否使用调试器在 error 发生的地方中断了行,并调查了局部变量的值?另外:请制造minimal reproducible example。我的预感是:您正在访问vector 越界。
  • 您确定userInputCacheSize 不大于您的cacheSizeVector 大小吗?
  • @KyleKhalaf 是的,这就是问题所在!我将其更改为 cacheSizeVector.size();。现在可以了!

标签: c++ if-statement vector string-comparison


【解决方案1】:

您正在使用循环中的越界索引访问向量。

        for(int i = 0; i <= userInputCacheSize; i++){
            if(cacheSizeVector[i] == linePerLine){    <<<<LINE OF ERROR!
                lruCounter[i] = lruCounter[i] + 1;
                cout << lruCounter[i] << endl;
                cout << cacheSizeVector[i] << " HIT!" << endl;
                cout << cacheSizeVector.size() << endl << endl;
            }
        }

在 for 循环的条件中使用 i &lt;= userInputCacheSize 是不对的。应该是:

        for(int i = 0; i < cacheSizeVector.size(); i++){

当然,这假设i 将是访问lruCounter 元素的有效索引。如果不是这种情况,您必须相应地更改您的代码。

【讨论】:

  • 哇!谢谢您的帮助!那是个问题......如此简单的修复和提示。我花了几个小时试图弄清楚。谢天谢地,我加入了 StackOverflow!
  • @AndresValdez,不客气。很高兴我能提供帮助。
  • 您好,打扰了。我遇到了非常相似的事情。它不再停在 4096,但现在停在 16384。同样的错误和一切。代码基本相同,只是把你告诉我的“userCacheSize”改成了->“cacheSizeVector.size()”。
  • @AndresVal,如果不查看整个程序,我很难看出哪里出了问题。尝试使用调试器。
猜你喜欢
  • 2015-01-04
  • 2021-03-07
  • 2017-08-10
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多