我正在学习在Xcode中花费最后一个学期编码后使用Visual Studio。我写了一个简单的函数来洗牌持有家餐馆中字符串不同的名称如下矢量:矢量下标超出范围错误的可能原因是什么?
#include <vector>
#include <string>
#include <ctime>
//shuffles all the restaurants
void shuffler(vector<string>& restaurvector)
{
srand(time(NULL));
vector<string> shuffled;
long initialSize = restaurvector.size();
for (int i = 0; i < initialSize; i++)
{
// get a random number between 0 and the current vector size
int randomOfRest = rand() % restaurvector.size();
// locate a random element in the original vector and set it as
// the next element in the shuffled vector
shuffled.push_back(restaurvector[randomOfRest]);
// delete the element that was copied and shift remaining elements
for (int j = randomOfRest; j < restaurvector.size(); j++)
{
restaurvector[j] = restaurvector[j + 1];
}
restaurvector.pop_back();
}
restaurvector = shuffled;
cout << "\nThe restaurant vector has been shuffled.\n";
}
当我运行在Xcode此相同的程序,它编译和运行完美。当我运行从Visual Studio这个程序,我得到的是这样的一个运行时错误:
我检查了我的代码,使不存在的不确定我是不是引用的元素,但无论是什么我这样做,它运行不正常。发生了什么?为什么它不像在Xcode中那样在Visual Studio中运行?
'restaurvector.size() - 1'超出范围时'restaurvector [j + 1]'。 – Matt 2015-04-02 00:49:11