Personal tools
You are here: Home Eddie's diary Challenge C++

Challenge C++

Posted by (A|E)ddie at Sep 23, 2010 11:35 PM |

Because I want to program by C++,
I start studying basics of C++.

First of all, I wrote a code which convert string that consists of numbers to integer vector.

vector<int> stringToIntVector(string str)
{
vector<int> result(str.size());
for (int i = 0; i < str.size(); i++)
{
if ('0' <= str[i] && str[i] <= '9')
{
result[i] = (int) (str[i] - '0');
}else{
result.clear();
break;
}
}
return result;
}

I feel there are not enough error handling.

Anyway, please give me a comment if you notice anything about my code or my English.

 

Added on 09/28/2010

Rewrite the code to follow Mr. Hat's suggestion. (He gave me a comment in Japanese.)

std::vector<int> stringToIntVector(std::string str)
{
std::vector<int> result(str.size());
for (int i = 0; i < str.size(); i++)
{
if ('0' <= str[i] && str[i] <= '9')
{
result[i] = str[i] - '0';
}else{
result.clear();
break;
}
}
return result;
}

Rewrite points are below.

  1. Specify the namespace "std". (I wrote "using namespace std" in the test code and forgot about it.)
  2. Delete the int cast because that does nothing. I'm not sure this is the right decision.
Document Actions
« June 2019 »
June
SuMoTuWeThFrSa
1
2345678
9101112131415
16171819202122
23242526272829
30