error attempt to erase the specific position in a string vector.
Nov 30, 2010 at 3:33pm UTC
I having a problem to execute the algorithm erase. My program is planned to erase the position of a string. Is it necessarily use iterator together with erase?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
void Student:: dropStudent()
{
string target;
int position;
cout<<"Student's name search : " ;
getline(cin,target);
vector<string>::iterator it;
it=find(namePtr.begin(),namePtr.end(),target);
if (it==namePtr.end())
cout<<"No student record. \n" ;
else
{
cout<<"Student " <<target<<" found. \n" ;
for (int i =0; i<namePtr.size();i++)
{
if (*it==namePtr[i])
position=i;
}
cout<<"At position :" <<position+1<<endl;
cout<<"Drop this student record? (y/n) : " ;
int sum=0;
namePtr.erase(namePtr.begin()+position);
cout<<"Deleted : " <<namePtr[position];
facPtr.erase(facPtr.begin()+position);
cout<<"Deleted : " <<facPtr[position];
for (int h=0;h<=position;h++)
{
sum=sum+numCourse[h];
}
sum=sum - numCourse[position];
cout<<"Student's name : " <<namePtr[position]<<endl;
cout<<"Faculty : " <<facPtr[position]<<endl;
cout<<endl;
cout<<"Course(s) : \n" ;
for (int j=sum;j<numCourse[position]+sum;j++)
{
cout<<subPtr.erase(subPtr.begin()+j)<<endl;
cout<<"Deleted : " <<subPtr[j];
}
}
}
Nov 30, 2010 at 4:13pm UTC
What problem are you having?
1 2
namePtr.erase(namePtr.begin()+position);
cout<<"Deleted : " <<namePtr[position]; //you just erase it, what do you expect?
find(namePtr.begin(), namePtr.end(), target) - namePtr.begin()
This will give you the position
Dec 1, 2010 at 12:02am UTC
I couldn't compile the whole program as it give me
no match for "the operator<<" in std:: cout << <<<std:: vector<std:string,std::allocator<std:: string> .... etc
for this line
1 2
error: cout<<subPtr.erase(it)<<endl; // i modify my code a little to this. before this is
//cout<<subPtr.erase(subPtr.begin()+j)<<endl;
Dec 1, 2010 at 5:03am UTC
What do you want to do?
subPtr.erase(it)
returns an iterator, possibly invalid (end). What do you want to print?
Dec 1, 2010 at 5:33am UTC
I want to erase the element of a string but my console won't compile because there is an error.
Dec 1, 2010 at 6:30am UTC
Then why are you trying to [code]cout<<[/cout] it?
Dec 1, 2010 at 6:34am UTC
you should echo before whatever you want to print
then I guess it will wok
ok
Regards
Lubi
Dec 1, 2010 at 6:35am UTC
any one have idea about how to analyse memory of a software using C++ , or is there any algorithm to analyse memory
plz plz do help me
Regards
Lubi
Dec 1, 2010 at 7:11am UTC
save the data (string in this case) before you erase it and then print it out. Like
1 2 3
const string deleted_name = namePtr[position];
namePtr.erase(namePtr.begin()+position);
cout<<"Deleted : " <<deleted_name;
or just print it before you erase it
1 2
cout<<"Deleted : " <<namePtr[position];
namePtr.erase(namePtr.begin()+position);
Topic archived. No new replies allowed.