Using containers to appear vector subscript out of range and similar errors

Source: Internet
Author: User

Newspaper this mistake will pop up a window, seemingly memory overflow, what this is because the vector stored data beyond the size of the vector caused.

Here's how to fix it:

After vector<string> vector, it is not possible to directly pass such as:

Vector[0] = "AA"

VECTOR[1] = "BB" to be assigned, which can result in an out-of-bounds. (Subscript is the modification is not inserted, if you want to use subscript, you need to ensure that the initialization time has enough elements, generally with push_back ())

First, use the Tagseq.resize (n) statement to adjust the size of the vector to the initial length, and then you can assign the value in the above way. The key is to learn to set the initial length of the container with the resize () function.

Another way, after vector<string> vector, is to call the vector push_back ("AA") method to add data to the vector, the method will automatically request memory, So the size of the vector can be gradually increased, will not cross the border.

There is also the use of containers, often in accordance with certain criteria to determine the container through the push_back () function to add elements, but may have never met the conditions, that is, there is no element added to the container, at this time if the container through the subscript to access such as v[n-1] or through some functions to access the container such as V.back (), V.front () and so on will appear subscript out of error (memory overflow), because there is no element in V, the length of V or v.size () equals 0, so like v[n-1], V.front () And so there is no meaning, so there will be errors, which is easy to ignore the place. If you have to use a certain function such as the subscript access or the container, you can first add an if condition if (!v.empty ()), that is, the above access operation is feasible in case of v non-null.

Using containers to appear vector subscript out of range and similar errors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.