[英]Insert into a vector in alphabetical order
I am trying to insert into this Vector (mCards) in alphabetical order. 我试图按字母顺序插入此Vector(mCards)。 I can't use sort - it must be inserted in alphabetical order!
我不能使用sort-必须按字母顺序插入! Right now...I'm inserting in reverse.
现在...我要反向插入。 I can't figure out how to get this to insert in correct alphabetical order!!
我不知道如何使它以正确的字母顺序插入! Can anyone help me?
谁能帮我? Thank you!
谢谢!
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();
}
}
}
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. 如果要排序的容器,则可以查看
std::map
和std::set
或它们的multi变量(如果您有重复的值)。
To insert into a sorted vector, the right way to do it is to use std::upper_bound
要插入排序的向量中,正确的方法是使用
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 如果卡没有有效的
operator<
,请使用这样的谓词
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.