Hi so I am having trouble figuring out how to search though arrays, in particular with string. I have more than one question but here goes for now.
My first question is linear search. Modify the searchList function given below so that it searches for a given name (not an int) the functions returns an int which is the index of the name found. If -1 is returned then say name is not found otherwise write out the name and the mark for that name. So this is what I did and I have no clue whether it is correct. I am also confused because the wording of this sounds like a 2D array, how does it store the name AND the mark?
int searchList (const string list[], int numElems, string value)
{
int index = 0; // Used as a subscript to search array
int position = -1; // To record position of search value
bool found = false; // Flag to indicate if value was found
while (index < numElems && !found)
{
if (list[index] == value) // If the value is found
{
found = true; // Set the flag
position = index; // Record the value's subscript
}
index++; // Go to the next element
}
if (position ==-1)
{
cout << “ Name not found.” << endl; << endl;
}
else
{
cout << list[position]; // Confused here, how do I output the name and mark?
}
return position; // Return the position, or -1
I cannot really build it in VS because I don't know how I would at this point. My book doesn't touch on string searches so I am confused.
int main() { int foundPos = searchList(yourArray, number_of_items, "Bob"); if ( foundPos != -1 ) { //output the name and position }In other words, and again, the function searchList doesn't do output -- all it does is return info.