Array help

closed account (NURz8vqX)
I need to remove elements from an array. Is this achievable? I have tried converting it to a vector, but I can't seem to get it correct without tons of errors. Here is my code. I want to remove a name, then print the list again. Please ignore the part about the age, i do not have to store that and will be used later on. I am new to c++, so please keep that in mind. Thank you.



#include <iostream>
#include<string>
using namespace std;


int main()
{
string last;
int age;

cout << "Please enter your last name: ";
cin >> last;
cout << "Please enter your age: ";
cin >> age;


string names[] ={"Albert","Rogers","White","Wong",last};

int size = sizeof(names)/sizeof(string);

for (int i=0; i < size; i++){
cout << names[i] <<endl;

}


}
You're better off using a vector rather than implementing it yourself, because the STL vector's erase() function is exactly what you need. Here's a tutorial on the vector class: http://www.cprogramming.com/tutorial/stl/vector.html

However, if you're going to use the STL anyways, you're better off using a list, since it has better performance and the syntax is pretty much nearly equivalent. There are plenty of STL tutorials which will cover vectors, lists, iterators, etc.

If you're fine with your array having "holes" you could just "remove" a name by setting the value to an empty string "" and skipping over it. Of course if you need to add/remove things over time, this approach won't work. The proper way to do it is to dynamically grow and shrink your data structure, which the STL containers do for you.
closed account (NURz8vqX)
Thank you, I was able to create a vector than use erase to do what I needed it to. Thanks again.
Topic archived. No new replies allowed.