Sunday, July 12, 2009

C++ Coding problem?

Can anyone suggest the error in this section of code? I am using vectors in a program for a phone book..... this function is to search for a person's phone number:





int search(const string%26amp; name, const vector%26lt;string%26gt;%26amp; nameList, const vector%26lt;int%26gt;%26amp; teleNumList)


{


vector%26lt;string%26gt;::iterator pos = find(nameList.begin(), nameList.end(), name);


int i = nameList(pos);





int Number = teleNumList[i];





return Number;





}





Anyone? Anyone? Bueller? Bueller?

C++ Coding problem?
Your problem is the line


int i = nameList(pos);





Because you want the index of the name you just found. But what that code does is it ends up retrieving the name itself, nit its index. And assigning the name to int i is meaningless, it is like assigning a string to an integer.





You need to convert the iterator pos to the index. The general way of doing that is


index = iter - cont.begin()





Applying that logic, your line becomes:





int i = pos - nameList.begin();





After that, the rest of the code should work.





One word of caution: when you search the name in the nameList, you should also check for the condition when the name was not found. The siplest way to do so is:





int search(const string%26amp; name, const vector%26lt;string%26gt;%26amp; nameList, const vector%26lt;int%26gt;%26amp; teleNumList)


{


vector%26lt;string%26gt;::iterator pos = find(nameList.begin(), nameList.end(), name);





if (pos != nameList.end())


{


int i = pos - nameList.begin();


if( (int) teleNumList.size() %26gt;= i + 1 )


return teleNumList[i];


else


{


cout %26lt;%26lt; "Phone list is shorter than name list." %26lt;%26lt; endl;


return -1; //or anything of your choice that denotes error


}


}


else


{


cout %26lt;%26lt; "Name not found." %26lt;%26lt; endl;


return -1; //or anything of your choice that denotes error


}





}
Reply:i think u r missing %26amp; reference operator before variables
Reply:Adamly, Anderson... Anderson? [HERE!]





Are you sure teleNumList contains actual telephone numbers? The teleNumList is defined as a vector of ints, but it's quite uncommon to represent phone numbers as ints --as they usually contain spaces, dashes and brackets...





[I deleted my unrelated suggestion, as it doesn't apply...]
Reply:Could not find the issue, may be you can contact a C++ expert at websites like http://oktutorial.com/


No comments:

Post a Comment