I wrote a simple data handler class.
I would like to know if I can make my class more simple and efficient for doing the identical feature.
My Code :
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class MyData
{
public:
void add(const pair<string *, int> &elem)
{
size_t index = findIndex(elem.first);
if (index != -1) //if key exists, update the value
{
myVec[index].second = elem.second;
return;
}
myVec.push_back(elem);
}
void remove(string *strPtr)
{
size_t index = findIndex(strPtr);
if (index != -1)
myVec.erase(myVec.begin() + index);
}
void sort()
{
std::sort(myVec.begin(), myVec.end(), comp);
}
void print()
{
for (size_t i = 0; i < myVec.size(); ++i)
{
cout << *myVec[i].first << " : " << myVec[i].second << '\n';
}
}
private:
size_t findIndex(string *strPtr)
{
auto it = find_if(myVec.begin(), myVec.end(), [&](pair<string *, int> const & ref)
{
return ref.first == strPtr;
});
if (it != myVec.end())
return std::distance(myVec.begin(), it);
return -1;
}
static bool comp(const pair<string *, int> &a, const pair<string *, int> &b)
{
return a.second < b.second;
}
vector<pair<string *, int>> myVec;
};
int main()
{
string fruits[] = {"Apple", "Banana", "Orange", "Grapes", "Lemon"};
MyData data;
data.add(make_pair(&fruits[0], 13));
data.add(make_pair(&fruits[1], 52));
data.add(make_pair(&fruits[2], 33));
data.add(make_pair(&fruits[3], 8));
data.add(make_pair(&fruits[4], 22));
data.add(make_pair(&fruits[1], 17));
data.sort();
data.remove(&fruits[4]);
data.print();
}
The Result :
Grapes : 8
Apple : 13
Banana : 17
Orange : 33
Program ended with exit code: 0
std::map
for the task? \$\endgroup\$std::map
so I decided to go withstd::vector
. Please see my other post: stackoverflow.com/questions/52055430/… \$\endgroup\$