如何利用STL在本期中获得更好的结果和性能

how to make use of STL's for better result and performance in this issue

本文关键字:更好 结果 性能 STL 何利用      更新时间:2023-10-16

我有一组字符串,格式为: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

将每个国家名称映射到可能组合的矢量。典型的工作流程如下:

  1. 分析输入字符串
  2. 存储分析结果
  3. 查询存储容器

因此,从结果的结构开始:

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;

如果你有任何问题,请发表评论,这样我可以改进这个答案。