如何利用STL在本期中获得更好的结果和性能
how to make use of STL's for better result and performance in this issue
我有一组字符串,格式为:country/currency/minimum_amount
例如:
US/USD/18
US/EUR/20
DE/USD/22
GB/EUR/19
假设我有每个国家、货币和最低金额的下拉列表。一旦我选择了国家,我应该从上面的一组字符串中获得货币和最小金额的可能组合。
前任。一旦我在dropdown_1中选择国家为美国,那么货币(下拉列表)应该显示-美元和欧元以及min_amt-18和20\例2:一旦我在dropdown_2中选择Currency作为USD,那么country(下拉列表)应该显示-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
由于我使用字符串::find,它甚至显示"USD",因为它包含"US",但它不应该用于我的用例。
有人能为这个用例提出一个更好的解决方案吗?这样我就可以提高结果和性能。
我会使用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;
如果你有任何问题,请发表评论,这样我可以改进这个答案。
相关文章:
- C++:将控制台输出存储在宏中更好吗
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 初始化具有非默认构造函数的std::数组项的更好方法
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么新的随机库比std::rand()更好
- 寻找一种更好的方法来表示无符号字符数组
- 哪种方法更好,性能明智
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 什么是更好的做法?通过指针或标识符传递类成员?
- 寻求更好地理解标准::访问
- 线程消息传递或更好:在"大师班"中访问其他班级的成员
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 如何更好地检查两个 char 变量是否在一组值中?
- 有没有更好的方法对C++中的三个整数进行排序?
- 什么模板用法在阶乘中更好
- 平面缓冲区可以利用向量中的 0 吗?还是其他小波比哈尔变换更好?
- 我们应该如何使用枚举类进行索引(或者我们应该更好地避免这种情况)?
- 在QT列表中存储DB的查询结果的更好方法
- 如何利用STL在本期中获得更好的结果和性能
- 在c++中,任何更好的方法都可以做到这一点,计算谜题的解决方案(49!结果,49个循环)