我有一些格式的字符串:country/currency/minimum_amount
例如:
US/USD/18
US/EUR/20
DE/USD/22
GB/EUR/19假设我的国家、货币和最低金额各有下降。一旦我选择了国家,我应该从上面的字符串中得到货币和最小金额的可能组合。
例如。一旦我选择国家为美国在dropdown_1,那么货币(下拉)应该显示-美元和欧元和min_amt - 18和20.\ ex。2:一旦我在dropdown_2中选择货币为美元,那么国家(下拉)应该显示- US和DE以及min_amt - 18和22。同样,第三次下跌也是如此。
我的解决方案,假设我在向量中有这些特定的字符串(name- myvector),那么我将使用以下方法检索字符串:
std::string str2("US"); // i need the strings that has country as US
string credt_fin_str;
for (unsigned j=0; j<myvector.size(); j++)
{
credt_fin_str = myvector.at(j);
std::size_t found = credt_fin_str.find(str2);
if(found != string::npos)
{
std::cout<<"creditfin found:"<<credt_fin_str<<std::endl;
}
}输出:
US/USD/18
US/EUR/20
DE/USD/22因为我使用了string::find,所以它甚至会显示“美元”,因为它包含"US“,但是它不应该用于我的用例。
有人能为这个用例提出更好的解决方案吗?这样我就可以提高结果和性能了。
发布于 2015-02-25 18:55:54
我会用std::map。
将每个国家的名称映射到可能组合的向量。这方面的典型工作流如下:
因此,从结果的结构开始:
struct CurrencyVal
{
string currency;
int minimum_ammount;
};它将存储在每个国家的载体中。这表示单个条目,如USD/18,与任何国家无关。
现在,让我们腾出一些空间来存储它:
std::map<string,vector<CurrencyVal>> dropdowns;它将将任何国家映射到可能的CurrencyVal值列表。现在让我们解析输入向量。假设输入向量是vector<string> input。
//Helper function, note the pos is passed by reference to modify it
string parseToToken(string& str, int& pos, char delim)
{
string result="";
for (; pos<str.length(); pos++)
{
if (str[pos] == delim)
break;
result+=str[pos];
}
pos++; //Skip the token
return result;
}
for (unsigned i=0; i<input.size(); i++)
{
int pos = 0;
string country;
CurrencyVal value;
country = parseToToken(input[i],pos,'/');
value.currency = parseToToken(input[i],pos,'/');
//stoi from <string> in C++11, if you are not using c++11, try with atoi(input[i].substr(pos).c_str())
value.minimum_ammount = stoi(input[i].substr(pos));
//Store the results
dropdowns[country].push_back(value);
}就这样。现在我们可以像这样查询这个结构:
vector<CurrencyVal> allForUs = dropdowns["US"];
for (unsigned i = 0; i < allForUs.size(); i++)
cout << allForUs[i].country << " - " << allForUs[i].minimum_ammound << endl;如果你有任何问题,发表评论,我可以改进这个答案。
https://stackoverflow.com/questions/28726732
复制相似问题