In practice, the vector series in c ++ -- Some vector exceptions

Source: Internet
Author: User

In practice, the vector series in c ++ -- Some vector exceptions

Today, we will write some vector exceptions that can be captured.

Out_of_range
The array is out of bounds. The vector automatically increases the capacity, but if the index exceeds the current size, an exception is thrown.

# Include
  
   
# Include
   
    
Using namespace std; int main () {vector
    
     
V (4); std: cout <v [0] <std: endl; std: cout <v [1] <std: endl; std: cout <v [2] <std: endl; std: cout <v [3] <std: endl; std :: cout <v [4] <std: endl; // return 0 out of bounds ;}
    
   
  

In addition to using indexes, the following error occurs when vector. at () is used:

#include 
  
          // std::cerr#include 
   
          // std::out_of_range#include 
    
              // std::vectorint main (void) {  std::vector
     
       myvector(10);  try {    myvector.at(20)=100;      // vector::at throws an out-of-range  }  catch (const std::out_of_range& oor) {    std::cerr << "Out of Range error: " << oor.what() << '\n';  }  return 0;}
     
    
   
  

Std: length_error
When vector is used, std: length_error is rarely thrown. However, if you neglect to write such code:

#include 
  
          // std::cerr#include 
   
          // std::length_error#include 
    
              // std::vectorint main (void) {  try {    // vector throws a length_error if resized above max_size    std::vector
     
       myvector;    myvector.resize(myvector.max_size()+1);  }  catch (const std::length_error& le) {      std::cerr << "Length error: " << le.what() << '\n';  }  return 0;}
     
    
   
  

Vector * pData;

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.