Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created June 2, 2011 16:36
Show Gist options
  • Save mastbaum/1004761 to your computer and use it in GitHub Desktop.
Save mastbaum/1004761 to your computer and use it in GitHub Desktop.
A comparison on C-style pointer arrays and STL vectors
#include<iostream>
#include<vector>
/** Attention pointer lovers! You can declare C-style arrays as pointers and
* assign them to the reference returned by "new"ing a normal C array.
*
* But don't. Please.
*/
int main()
{
// why do this...
int *a;
a = new int[5];
a[3] = 2;
a[4] = 1;
std::cout << "a:" << std::endl;
for(int i = 0; i < 5; i++)
std::cout << a[i] << std::endl;
// ...when you can do this?
std::vector<int> b(5);
b[3] = 2;
b[4] = 1;
std::cout << "b:" << std::endl;
for(size_t i = 0; i < b.size(); i++)
std::cout << b[i] << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment