Using std::string::at for If statement

When attempting the challenge, i did everything the same with one minor difference. My actual if statement made use of the std::string::at function that i found online when looking to access characters within a string:

//loop through all letters in the guess
int32 HiddenWordLength = MyHiddenWord.length();
for (int32 i = 0; i < HiddenWordLength; i++)
{
	//compare letters against the hidden word
	for (int32 j = 0; j < HiddenWordLength; j++)
	{
		//if they match then
		if (Guess.at(i) == MyHiddenWord.at(j))
		{
			//increment bulls if they're in the same place
			if (i == j)
			{
				BullCowCount.Bulls++;
			}
			//increment cows if they're not
			else
			{
				BullCowCount.Cows++;
			}
		}
	}
}

Is there any reason to not use this approach and instead go with the way suggested in the video? Or is it just a matter of personal preference? Relatively experienced with object-oriented programming but quite new to C++ so don’t want to create any nasty habits :slight_smile:

The difference is that string::at will do bounds checking, and will throw an exception if your index is out of range, where the brackets operator will try to access the memory anyways and have undefined behavior. Because of these checks, brackets is slightly faster than string::at, so if you write your for loops properly brackets is the way to go, although string::at may be more helpful for debugging.

Brilliant, exactly the kind of information i was looking for. Thank you! :slight_smile:

Privacy & Terms