我有一个结构,其中有一个 vector
vector<int> accept;
在我的程序中,当我尝试在特定索引处插入一个值时。我收到此错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
在循环的每次迭代中,我递增 AlphabetCounter 并在该特定索引处放置一个值,如下面给出的代码:
AlphabetCounter=AlphabetCounter+1;
NewNextStateDouble.accept.at(AlphabetCounter)=1;
AlphabetCounter=-1 开始循环之前。
我不明白为什么会出现超出范围的错误。
最佳答案
您只能使用以下这两种方法来增长 vector :
使用 resize()
方法:
std::vector<int> my_vector;
v1.resize( 5 );
使用 push_back()
动态增加 vector 大小的方法:
std::vector<int> my_vector;
for( int i = 0; i != 10; ++i )
{
my_vector.push_back( i );
}
std::cout << "The vector size is: " << my_vector.size() << std::endl;
在您的情况下,您必须知道下标不会添加元素,正如标准所说:
The subscript operator on vector (and string) fetches an existing element; it does not add an element.
下面还有一些关于订阅的建议。
Subscript Only Elements that are Known to Exist!
It is crucially important to understand that we may use the subscript operator (the
[]
operator) to fetch only elements that actually exist. ( For example, see the code below )It is an error to subscript an element that doesn’t exist, but it is an error that the compiler is unlikely to detect. Instead, the value we get at run time is undefined. (usually, an
out_of_range
exception)Attempting to subscript elements that do not exist is, unfortunately, an extremely common and pernicious programming error. So-called buffer overflow errors are the result of subscripting elements that don’t exist. Such bugs are the most common cause of security problems in PC and other applications.
vector<int> ivec; // empty vector
cout << ivec[0]; // error: ivec has no elements!
vector<int> ivec2(10); // vector with ten elements
cout << ivec2[10]; // error: ivec2 has elements 0 . . . 9
关于C++ vector :std::out_of_range 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067705/