Improving my C++ function?

closed account (DGvMDjzh)
I'm kinda sorta new to C++ and I made a simple function that would retrieve certain word(s) from a string.

Usage:

WFS("Hello world 123 lawl test",2) returns "world"
WFS("Hello world 123 lawl test",-3) returns "123 lawl test"

You get the picture. I'm looking for a way to improve the function's speed. Don't get me wrong it's pretty fast, but the faster the better :) Any ideas?

Code:

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
string WFS(string sentence,int num) {
if (num < 0) {
num = num * -1;
string temp;
string word;
vector<string> sV;
istringstream instr(sentence);
while (instr >> word) {
sV.push_back(word);
if (sV.size() >= num) temp = temp + word + " ";
}
if (sV.size() >= num) return temp;
else return "001";
}
else {
num = num - 1;
string word;
vector<string> sV;
istringstream instr(sentence);
while (instr >> word) {
sV.push_back(word);
}
if (sV.size() >= num) return sV[num];
else return "001";
}

The function interface is a little weird. If I specify a positive value N, I get just the Nth word. If I specify a negative value N, I get the last N words. If that's the behavior you want, then I'd split it into two functions first off.

In either case, there is no need to maintain a std::vector<> of words. This will improve performance. I'd replace the std::istringstream with a simple state machine. It makes the
code a little more complex because istringstream deals with consecutive spaces, but it will
speed up your code.

I'd make use of std::string::reserve to ensure that the string isn't reallocated each time you add a word or character to it.
Without seeing the logic of the code, I suggest some changes,

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
std::string WFS(const std::string &sentence, int num) {

	std::string word;
	std::vector<std::string> sV;
	istringstream instr(sentence);

	if (num < 0) {
		num = -num;
		std::string temp;
		while (instr >> word) {
			sV.push_back(word);
			if (sV.size() >= num)
				temp = temp + word + " ";
		}
		if (sV.size() >= num)
			return temp;

	} else {
		num--;
		while (instr >> word) {
			sV.push_back(word);
		}
		if (sV.size() >= num)
			return sV[num];
	}

	return (std::string("001"));
}


Last edited on
Topic archived. No new replies allowed.