In the pairstring vector, int: When adding a new string, check if a future string has the same value as a string already added

-1

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

So, I would like to add string, int pairs into a vector, except that, to avoid redundant pairs, check if the string already exists and instead of adding a duplicate value to the vector, update an existing one. The intent is to store a player's name and punctuation. What is the best way? Is it 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)); 
 }
}
    
asked by anonymous 09.03.2018 / 00:47

1 answer

0

It is possible to work with vector, but the search would be linear. However with map you are using Rubro-Negras Arvores, which allows a faster search of already inserted pairs.

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: link

    
10.03.2018 / 06:59