'Insert into a vector in alphabetical order
I am trying to insert into this Vector (mCards) in alphabetical order. I can't use sort - it must be inserted in alphabetical order! Right now, I'm inserting in reverse. I can't figure out how to get this to insert in correct alphabetical order!
void Rolodex::Add(Card& card)
{
vector<Card>::iterator temp;
if (mCards.size() != 0)
{
for(vector<Card>::iterator it = mCards.begin(); it != mCards.end(); ++it)
{
Card& currentCard = *it;
temp = it;
int compareResult = currentCard.GetLastName().compare(card.GetLastName());
if (compareResult <= 0)
{
mIteratorNumber = it - mCards.begin();
mCards.insert(temp, card);
return;
}
}
}
else
{
mCards.push_back(card);
for(vector<Card>::iterator it = mCards.begin(); it != mCards.end(); ++it)
{
mIteratorNumber = it - mCards.begin();
}
}
}
Solution 1:[1]
If you wants a sorted container, you may instead look at std::map and std::set or their multi variant if you may have duplicated values.
To insert into a sorted vector, the right way to do it is to use std::upper_bound
myCards.insert( std::upper_bound( begin(myCards), end(myCards), card), card );
If the card do not have a valid operator<, use a predicate like this
auto it = std::upper_bound( begin(myCards), end(myCards), card,
[] ( Card const & a, Card const & b ) {
return a.GetLastName().compare(b.GetLastName()) < 0;
} );
myCards.insert( it, card );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
