In the vector category pair<string, int>: When adding a new string, check whether a future string has the same value as an already added string

Asked

Viewed 56 times

-1

And if so, change the value of the previously added pair instead of adding a new pair.

So, I’d like to add string pairs, int into an array, only, to avoid redundant pairs, check if the string already exists and instead of adding a duplicate value to the array, update an existing one. The intention is to store a player’s name and score. What is the best way? It is possible?

#include <bits/stdc++.h>
#define psi pair<string, int> 
#define mp make_pair

using namespace std;

int numround(int&);
void validate(string, int);


int main(){
int n, score = 0;
string name = "";
vector<psi> v;

numround(n);
for (int i = 0; i < n; ++i){

    cout << "Enter name[32] and score[-1000 ~ 1000]: " << endl;
    cin >> name;
    cin >> score;
    validate(name, score);
    v.push_back(mp(name,score)); 
 }
}

1 answer

0

It is possible to work with vector, but the search would be linear. But with map you are using Red-Black Trees, which allows a faster search of pairs already inserted.

std::map<std::string,int> pontuacao;

to insert just

std::map<std::string,int>::iterator busca = pontuacao.find(name);
if(busca != pontuacao.end()){
    busca->second = score;
} else {
    pontuacao.insert(std::pair<std::string,int>(name, score));
}

source and examples: http://www.cplusplus.com/reference/map/map/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.