Safe To Modify std :: pair <U, V> :: first in pairs vector?

I am currently working on a DNA database class and I am currently linking each row in the database with both a match score (based on edit distance) and an actual DNA sequence, is it safe to modify this path first within an iteration loop ?

typedef std::pair<int, DnaDatabaseRow> DnaPairT;
typedef std::vector<DnaPairT>          DnaDatabaseT;

// ....

for(DnaDatabaseT::iterator it = database.begin();
    it != database.end(); it++)
{
    int score = it->second.query(query);
    it->first = score;
}

      

The reason I do this is because I can sort them by result later. I tried maps and got a compile error about the change in the first place, but maybe better than this to save all the sorting information later?

+1


source to share


2 answers


To answer your first question, yes. It is perfectly safe to modify the members of your pair, as the actual data in the pair does not affect the vector itself.

edit: I got the feeling that you were getting an error when using a card because you were trying to change the value of an first

inner card pair. This will not be permitted because this value is part of the inner workings of the card.

As stated by dribeas :

In maps that you cannot change at first, as this will violate the invariant of the map being a sorted balanced tree


edit: To answer your second question, I don't see anything wrong with how you structure the data, but I would bind the database pointers to the DnaPairT

objects, not the objects themselves. This will significantly reduce the amount of memory that will be copied during the sort procedure.

#include <vector>
#include <utility>
#include <algorithm> 

typedef std::pair<int, DnaDatabaseRow> DnaPairT;
typedef std::vector<DnaPairT *>       DnaDatabaseT;

// ...

// your scoring code, modified to use pointers
void calculateScoresForQuery(DnaDatabaseT& database, queryT& query)
{
    for(DnaDatabaseT::iterator it = database.begin(); it != database.end(); it++)
    {
        int score = (*it)->second.query(query);
        (*it)->first = score;
    }
}

// custom sorting function to handle DnaPairT pointers
bool sortByScore(DnaPairT * A, DnaPairT * B) { return (A->first < B->first); }

// function to sort the database
void sortDatabaseByScore(DnaDatabaseT& database)
{
    sort(database.begin(), database.end(), sortByScore);
}

// main
int main()
{
    DnaDatabaseT database;

    // code to load the database with DnaPairT pointers ...

    calculateScoresForQuery(database, query);
    sortDatabaseByScore(database);

    // code that uses the sorted database ...
}
      

The only reason you might need to learn better methods is because your database is so huge that the sort cycle takes too long. If so, I would assume your function query

will be the one that takes the most of the processing time.

+5


source


You cannot change since the variable first from std :: pair is defined const



+1


source







All Articles