Reputation: 153
I have some set of strings in format : country/currency/minimum_amount
For example:
US/USD/18
US/EUR/20
DE/USD/22
GB/EUR/19
Let's say i have drop downs each for country, currency and minimum amount. Once i select the country, i should get the possible combination of currency and min amount from the above set of strings.
ex. Once i select country as US in dropdown_1, then currency(dropdown) should display - USD and EUR and min_amt - 18 and 20.\ ex. 2: Once i select Currency as USD in dropdown_2, then country(dropdown) should display - US and DE and min_amt - 18 and 22.. similarly for the third drop down as well.
My solution, Lets assume i have these specific strings in a vector(name - myvector), then I'm retrieving the strings using:
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;
}
}
Output:
US/USD/18
US/EUR/20
DE/USD/22
Since i using string::find, it displays even "USD" as it contains "US" but it shouldn't be for my use case.
can anyone suggest a better solution to this use case so that i can improve the result and performance.
Upvotes: 0
Views: 65
Reputation: 3065
I'd use std::map
.
Map each country name to vector of possible combinations. Typical workflow for this goes as follow:
So, start with structure for results:
struct CurrencyVal
{
string currency;
int minimum_ammount;
};
It will be stored in the vector for each country. This represents single entry like USD/18
and is not related to any country.
Now, lets make some space for storing it:
std::map<string,vector<CurrencyVal>> dropdowns;
It will map any country to list of possible CurrencyVal values. Lets now parse the input vector. Lets say the input vector is 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);
}
That's all. Now we can query this struct like this:
vector<CurrencyVal> allForUs = dropdowns["US"];
for (unsigned i = 0; i < allForUs.size(); i++)
cout << allForUs[i].country << " - " << allForUs[i].minimum_ammound << endl;
If you have any questions post a comment so I can improve this answer.
Upvotes: 2