Pig Latin Name

Hi!

I am reviewing the things I learned in the first half of my CPP class for this upcoming semester.

How can I optimize this following code?
I also think that when translating a name that starts with a vowel into pig latin is kind of funky.

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
43
44
#include <iostream>
#include <string>

std::string toLower(std::string str)
{
	for (int i = 0; i < str.length(); i++)
	{
		str.at(i) = tolower(str.at(i));
	}
	return str;
}
std::string pigLatin(std::string instr)
{
	std::string pigLatin1;

	if (instr[0] != 'a' && instr[0] != 'e' && instr[0] != 'i' && instr[0] != 'o' && instr[0] != 'u')
	{
		for (int i = 1; i < instr.length(); i++)
		{
			pigLatin1 += instr[i];
		}
		pigLatin1 = pigLatin1 + instr[0] + "ay";
	}
	else
	{
		pigLatin1 = instr + "way";
	}

	return pigLatin1;
}
int main()
{
	std::string first, last;
	std::cout << "Enter first and last name: ";
	std::cin >> first >> last;

	first = toLower(first);
	last = toLower(last);

	std::cout << "\nFirst name (Pig Latin): " << pigLatin(first);
	std::cout << "\nLast name (Pig Latin): " << pigLatin(last);
	return 0;
}
Last edited on
.at is slower than [] access.

could we optimize the big vowel condition... ?
at worst you could have vector bool where vowels are true such that if (vowels[instr[index]]) at the cost of the memory for the lookup table.

to-lower can be a one-liner with std::transform ... can you do that? don't need a function.
Last edited on
@jonnin
thanks for your reply!

could we optimize the big vowel condition... ? 

how would I do that? we haven't really covered vectors in the first half of the course...
let me read over the chapter and i'll come back with my attempt.

to-lower can be a one-liner with std::transform ... can you do that? don't need a function. 

we've only been taught the basic libraries, and we've been manually coding things like sort, min/max, tolower/toupper stuff.
vector<bool> table(256) = {false};
table['a'] = true; //you can hard code the initialization above for these or find some way to do them one time
table['e'] = true;
etc...
then as above
if( table[letter]) //is vowel
else //isn't


and from the web..
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });


play with those ideas, google around on the transform if you need to. I just lifted it from a quick search, I have to run.
Last edited on
Topic archived. No new replies allowed.