Editing a vector element

I need to make a function that can choose a single vector element erase it and insert a new value in its place. The new value has to be a string. I have some code that I started on, but I think that I need to do some converting using sstream, I don't know. Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void editFile (vector<string> &equation)
{
     dispFile(equation);
     
     int edit;
     string data;
     
     cout << "Choose the question to edit: ";
     getline (cin, edit);
     
     int element = equation.erase(edit-1);
     cout << "Enter new data: ";
     getline (cin, data);
     equation.insert(element, data);     
}
The display function looks like this:

1
2
3
4
5
6
7
void dispFile (vector<string> equation)
{
     for (int i = 1; i < equation.size(); i++)
     {
         cout << i << ": " << equation[i-1] << endl;
     }
}
Last edited on
Erasing and inserting is criminally inefficient with vector. You don't need to do all that.. just change the string directly.

Replace lines 11-14 with this:
1
2
     cout << "Enter new data: ";
     getline (cin, equation[edit] );


Other than that.. what exactly is your problem?
My program is a teachers program for creating simple quadratic questions for students (eg. 3x^2 + 2x - 9). The teacher can write an entire list of questions with my program and save them to a file. The program can also display the current list again, but now I want to have another option in my menu that allows the teacher to look at the list and choose one of the questions and change it. Then after they could re-save the file or continue to edit more questions. The display would show a numbered list:

1. 10x^2 - 5x + 25
2. 81x^2 + 27x - 54
3. etc..
Instead of erasing and inserting, you can update the element directly.
The following code would suffice.

cout << "Choose the question to edit: ";
getline (cin, edit);
cout << "Enter new data: ";
getline (cin, data);
equation[edit-1] = data;
Topic archived. No new replies allowed.