我的矢量突然停止有什么问题?

时间:2017-04-28 23:57:23

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

我在循环到元素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";
        }

初始化的一些错误:

“{return __is_long()?__ get_long_size():__ get_short_size();}”&lt;&lt; EXC_BAD_ACCESS

1 个答案:

答案 0 :(得分: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 <= userInputCacheSize是不对的。它应该是:

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

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