Not logged in. Log in with GitHub. About Websheets.

List of all available Websheets


Viewing cpp/vectors/examples/vector_bad by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
PropertyValue
Description
html markup
shown to student
 
An example of a few things NOT to do on vectors
Public permissions remove
Remarks
Comments, history, license, etc.
 
remove
Engine
Template / Reference solution
 
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
   vector<int> nums1;     // 0-size "array" internally
   
\[
   nums1.resize(10);
\show:
   // Can't access with [i] notation if array is not of that size
   // This should cause a crash
   for(int i=0; i < 10; i++){
      nums1[i] = 0;  
   }
]\
   
   // better
   vector<int> nums2(10);  // 10-size array initialized with default values/garbage
   // This now does work
   for(int i=0; i < 10; i++){
      nums2[i] = 0;  
   }
   
   // Back to the original, we can increase the size of the array with .resize()
   nums1.resize(10);
   // This now works
   for(int i=0; i < 10; i++){
      nums1[i] = 0;  
   }
   // Or if we have a blank vector or want to increase size of array
   // we can use .push_back()
   vector<int> nums3;     // 0-size "array" internally
   
   // Can use push_back to add a value and increase array size if needed
   for(int i=0; i < 10; i++){
      nums3.push_back(0);  
   }
   
   return 0;
}
C++ test suite
json list of stdin/args tests
e.g. [{"stdin":"hi", "args":["4", "5"]},
{"stdin":"noargs"}]

to just run once with no input use [{}]
 
[
   {}
]
Solution visibility remove
Is example?
i.e., just a demo
remove


Optional properties:

Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.