Efficient way to remove duplicate strings after adding their key values How can I remove duplicate strings from a std::vector&lt;std::pair&lt;std::string,int&gt;&gt; after adding the int members of the pair and sorting them by their string members?

For example:

abc   4
abc   3
xy    1
xyzw  12
xy    4
abc   14


should produce the result:

abc   21
xyzw  12
xy    5


I have actually used std::vector&lt;Mystruct&gt; as the data structure, with:

struct Mystruct
{
    string s;
    int e;
};


and sorted them with respect to their string values and linearly iterated by adding the keys and removing duplicates, and again sorted according to their key values and ended up getting Time Limit Exceeded.

#include&lt;iostream&gt;
#include&lt;algorithm&gt;
#include&lt;vector&gt;
#include&lt;string&gt;
using namespace std;
#define ull unsigned long long
struct vec
{
    string s;
    ull e;
};
bool compare(vec v1, vec v2) {
    return v1.s &lt; v2.s;
}
bool comparenum(vec v1, vec v2) {
    return v1.e &lt; v2.e;
}
int main() {
    int q;
    cin &gt;&gt; q;
    string ss;
    ull ee;
    vector&lt;vec&gt; v(q);
    for (int i = 0; i&lt;q; i++) {
        cin &gt;&gt; ss &gt;&gt; ee;
        v[i].s = ss;
        v[i].e = ee;
    }
    sort(v.begin(), v.end(), compare);
    for (int i = 0; i &lt; v.size() - 1; i++) {
        if (v[i + 1].s == v[i].s) {
            v[i].e = v[i].e + v[i + 1].e;
            v.erase(v.begin() + i + 1);
            i--;
        }
    }
    sort(v.begin(), v.end(), comparenum);
    for (vec vv : v) {
        cout &lt;&lt; vv.s &lt;&lt; " " &lt;&lt; vv.e &lt;&lt; endl;
    }
    return 0;
}
Avoid using namespace std;

Importing all names of a namespace is a bad habit to get into, and can cause surprise when names like begin and size are in the global namespace.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

The exceptions to this rule are namespaces explicitly intended to be imported wholesale, such as the std::literals namespaces.

Avoid preprocessor macros

If you want a shorter name for a type, it's much safer to write

using ull = unsigned long long;


Personally, I'd give it a name that reflects what I want to use it for, rather than what it (currently) is.

Improve naming

What's the significance of vec as a name?  It's confusingly similar to vector, but it's used as an element of a vector.  Similarly, its members s and e convey nothing - consider name and count, if that's what they represent.

Simplify the logic

It's a lot easier to accumulate counts if you introduce a std::map to hold the sums:

std::map&lt;std::string,ull&gt; accumulator;
for (auto const&amp; element: v)
    accumulator[element.s] += element.e;

// write them back into the vector
v.clear();
for (auto const&amp; element: accumulator)
    v.push_back(vec{element.first, element.second});