c++ - 如何利用 STL 在这个问题上获得更好的结果和性能

标签 c++ string vector

我有一些格式的字符串集: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 as USD,那么 country(dropdown) 应该显示 - US 和 DE 以及 min_amt - 18 和 22.. 同样适用于第三个下拉列表。

我的解决方案, 让我们假设我在一个 vector (名称 - 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,它甚至显示“USD”,因为它包含“US”,但它不应该用于我的用例。

谁能针对这个用例提出更好的解决方案,以便我可以改进结果和性能。

最佳答案

我会使用 std::map .

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

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

因此,从结果结构开始:

struct CurrencyVal
{
    string currency;
    int minimum_ammount;
};

它将存储在每个国家的 vector 中。这表示单个条目,如 USD/18与任何国家无关。

现在,让我们腾出一些空间来存放它:

std::map<string,vector<CurrencyVal>> dropdowns;

它将任何国家映射到可能的 CurrencyVal 值列表。现在让我们解析输入 vector 。假设输入 vector 是 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++ - 如何利用 STL 在这个问题上获得更好的结果和性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726732/

相关文章:

c++ - char 的实现定义是否影响 std::string?

c++ - 有效数字递增

c++ - 我的程序崩溃了,我很困惑(c++)

c++ - Do-While(false) block 与返回的效率

string - R:将数据框行转换为字符向量

c++ - C++ 字符串中会发生缓冲区溢出吗?

string - 各种位串的模式搜索

c++ - 希望 std::string::operator[] 可以返回 unsigned char

C++ vector 插入开始

c++ - STL:为 vector 写入 "where"运算符