See this code. I need to change the value of a specific element in a 2D string vector using the iterator. I can use for loop with an index to do this. but here what i need is directly use the iterator to refer the element. something like (*ite)[0] = "new name"
Any idea? I added full working code here for your convenience
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
string convertInt(int number)
{
stringstream ss;
ss << number;
return ss.str();
}
int main()
{
vector<vector<string>> studentList;
for(int i=0; i<10; i++){
vector<string> student;
student.push_back("name-"+convertInt(i));
student.push_back(convertInt(i+10));
studentList.push_back(student);
}
vector<string> temp;
for(vector<vector<string>>::iterator ite = studentList.begin(); ite != studentList.end(); ++ite){
temp = *ite;
if(temp[0].compare("name-5")==0){
cout << "Changeing the name of student 5" << endl;
// I need to change the studentList[5][0] (original value not the one in temp vector) at here using iterator ite
}
}
return 0;
}
Because
temp = *itemakes a copy of vector(student), if you modify ontemp, it’s not modified on realstudentList, that’s why you need(*ite)[0] = "new name"to change value on real element.Using for loop is a bit “ugly“, use std::find_if instead of for loop:
Or use Lambda if C++11 is available: