矢量超出特定机器的范围?

时间:2014-04-18 04:35:03

标签: c++ vector

我的一个程序中有一个函数只在特定的机器上抛出错误。它在我的Windows机器上运行正常,但是当我在Linux机器上测试时,它会抛出一个超出范围的向量错误:

----------------------------------------------
          FINDING LONGEST WORD CHAIN
----------------------------------------------
The longest chain(s) are:

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check
Abort

这就是我的惯例:

void findLongestChain(vector<FlexArray<StringWrap>* >& chains) {
    int max;
    int maxIndex;
    vector<int> v;

    for(std::vector<int>::size_type i = 0; i != chains.size(); i++) { // iterate through vector
        int chainSize = getChainSize(chains, i);

        if(chainSize == max) { // just in case we have a tie
            v.push_back(i);
        }

        else if(chainSize > max) { // we have found a larger word chain breaking any previous ties
            max = chainSize;
            maxIndex = i;
            v.clear();
            v.push_back(i); 
        }
    }

    cout << "----------------------------------------------" << endl;
    cout << "          FINDING LONGEST WORD CHAIN          " << endl;
    cout << "----------------------------------------------" << endl;
    cout << "The longest chain(s) are: " << endl;

    for(std::vector<int>::size_type i = 0; i < v.size(); i++) {

        cout << "    Chain #" << v[i] << ": " << getWordChain( chains, v[i] ) << endl;
    }

    cout << endl;
    cout << "Each chain(s) contain " << getChainSize(chains, maxIndex) << " total words.";
}

无论如何,我以前从未见过这种情况。我想知道是否有人在不同的机器上有一些关于程序错误的一般提示/建议/经验,以及如何着手解决问题。

1 个答案:

答案 0 :(得分:4)

以下几行可能是罪魁祸首。

int max;
int maxIndex;

变量未初始化。尝试将它们初始化为合理的东西,看看情况如何。