将对象移到Vector C ++的前面 [英] Moving object to front of vector c++

查看:34
本文介绍了将对象移到Vector C ++的前面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 vector< Suggestions>finalSuggestions ,其中包含一个 string word 和一些 int num .

I have a vector<Suggestions> finalSuggestions that contains a string word and some int num.

如果这个单词满足某些条件,我想将该对象移到向量的前面,将其从原来的位置移走.

If this word meets some condition, I want to move that object to the front of the vector, removing it from wherever it was.

我可以使用 vector :: insert

for (auto &x: finalSuggestions) {
    if ( double((x.num)/(topword.num)) < 50)
    {
        finalSuggestions.insert(finalSuggestions.begin(),x);
        break;
    }
}

但是我不知道如何从列表中将其删除.

例如,对于任意向量 {1,2,3,4,50,6,7,8,9} ,如果50满足条件,则将其移到列表的最前面,并从其所在位置删除它,并返回 {50,1,2,3,4,6,7,8,9} .上面的代码返回 {50,1,2,3,4,50,6,7,8,9}

For example, for some arbitrary vector { 1,2,3,4,50,6,7,8,9 }, if 50 meets the criteria, move it to the front of the list and delete it from where it was, returning { 50,1,2,3,4,6,7,8,9 }. The code above returns { 50,1,2,3,4,50,6,7,8,9 }

我一直在寻找 vector :: erase ,但是我遇到了问题,而且花费的时间比应该的长.

I was looking into vector::erase, but I'm having problems, and its taking longer than it should.

我设想了一个简单的解决方案(但这显然行不通)

I envision a simple solution (but this obviously doesn't work)

for (auto &x: finalSuggestions) {
    if ( double((x.num)/(topword.num)) < 50)
    {
        finalSuggestions.insert(finalSuggestions.begin(),x);
        finalSuggestions.erase(x);
        break;
    }
}

我阅读了有关删除删除的习惯用法(这是我的实现方式):

I read up on the erase-remove idiom (here is my implementation):

 finalSuggestions.erase( remove( begin(finalSuggestions), end(finalSuggestions), x ), end(finalSuggestions) ); 

但是出现了我不理解的错误:

but am getting an error that I don't understand:

In instantiation of '_FIter std::remove(_FIter, _FIter, const _Tp&) [with _FIter = __gnu_cxx::__normal_iterator<Suggestion*, std::vector<Suggestion> >; _Tp = Suggestion]':|

推荐答案

对于 vector :: erase ,您需要一个迭代器,因此基于范围的 for 用过的.请改用简单的 for 循环.首先擦除一个元素,然后将其插入,因为 insert 会使迭代器无效:

For vector::erase you need an iterator, so range-based for can't be used. Use simple for loop instead. First erase an element, and then insert it, because insert invalidates iterators:

for (auto it = finalSuggestions.begin(); it != finalSuggestions.end(); ++it) {
    if (some_condition(*it)) {
        auto x = *it; // or std::move(*it)
        finalSuggestions.erase(it);
        finalSuggestions.insert(finalSuggestions.begin(), x /* or std::move(x) */);
        break;
    }
}

使用 std :: move 将允许您移动元素而不是复制元素,这可以节省一些周期.

Using std::move will allow you to move an element around instead of copying it, which may save you some cycles.

这篇关于将对象移到Vector C ++的前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆