查找向量中元素的索引并将其删除

Finding an index of element in vector and removing it

我有一个循环。如果某个条件为真,我需要将一个项目添加到向量中。相反,如果它是假的,我需要从向量中删除一个项目。

这是我重现我正在尝试做的事情的最佳尝试:

#include <iterator>
#include <vector>
#include <algorithm>
#include <memory>

struct Arrow
{
    std::vector<Arrow*> inRange;
};

int main()
{
    std::vector<std::unique_ptr<Arrow>> arrows;
    for (int i = 0; i < 10; i++)
        arrows.push_back(std::make_unique<Arrow>());

    for (int i = 0; i < arrows.size(); i++)
        for (int j = 0; j < arrows.size(); j++)
            if (i != j)
            {
                bool someCondition = true;//obviously can be false as well in the actual code
                if (someCondition)
                    arrows[i]->inRange.push_back(arrows[j].get());
                else
                {
                    std::vector<Arrow*> itr = std::find(arrows[i]->inRange.begin(),
                        arrows[i]->inRange.end(), arrows[i]);

                    int index = std::distance(arrows[i]->inRange, itr);
                    arrows[i]->inRange.erase(itr.begin(), index);
                }
            }
}

我完全不熟悉所有这些,也不知道出了什么问题。谢谢你的帮助。

错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0312   no suitable user-defined conversion from "std::_Vector_iterator<std::_Vector_val<std::conditional_t<true, std::_Simple_types<Arrow *>, std::_Vec_iter_types<Arrow *, size_t, ptrdiff_t, Arrow **, Arrow *const *, Arrow *&, Arrow *const &>>>>" to "std::vector<Arrow *, std::allocator<Arrow *>>" exists   steer away  C:\Users\me\source\repos\steer away\steer away\main.cpp 26  
Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0304   no instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Arrow *, _Alloc=std::allocator<Arrow *>]" matches the argument list   steer away  C:\Users\me\source\repos\steer away\steer away\main.cpp 30  
Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0304   no instance of function template "std::distance" matches the argument list  steer away  C:\Users\me\source\repos\steer away\steer away\main.cpp 29  
Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0304   no instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Arrow *, _Alloc=std::allocator<Arrow *>]" matches the argument list   steer away  C:\Users\me\source\repos\steer away\steer away\main.cpp 30  
Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0304   no instance of function template "std::distance" matches the argument list  steer away  C:\Users\me\source\repos\steer away\steer away\main.cpp 29  
Severity    Code    Description Project File    Line    Suppression State
Error   C2893   Failed to specialize function template 'iterator_traits<_Iter>::difference_type std::distance(_InIt,_InIt)' steer away  C:\Users\me\source\repos\steer away\steer away\main.cpp 29  
Severity    Code    Description Project File    Line    Suppression State
Error   C2664   'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>> std::vector<_Ty,std::allocator<_Ty>>::erase(std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>) noexcept(<expr>)': cannot convert argument 2 from 'int' to 'std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>'    steer away  C:\Users\me\source\repos\steer away\steer away\main.cpp 30  

我第二次选择 vector,但由于在循环中添加和删除项目可能很棘手而且效率不高,所以我会跳过添加和删除项目,从一个空容器开始,然后直接添加,所以这并没有直接解决你的问题,而是展示了我将如何解决你的问题。 (代码未编译,可能包含错误):


class Arrow
{
    /* ... */
    void clear_inrange_arrows(const std::size_t n)
    {
        m_inrange.clear();
        // This ensures just one dynamic allocation
        if(m_inrange.capacity()<n) m_inrange.reserve(n);
    }
    bool is_inrange_of(const Arrow& const other) const noexcept { /* ... */ }
    void add_inrange_arrow(const Arrow& const other)
    {
        m_inrange.push_back(&other);
    }

 private:
    std::vector<const Arrow*> m_inrange; // Arrows in range, owned by 'World'
};

// Allow me introduce something that manages
// the memory and performs the operation
class World
{
    /* ... */
    std::vector<Arrow> all_the_arrows;

    /* ... */
    void precalculate_whos_inrange()
    {
    // For each existing arrow (you could use `auto` here)...
    for(std::vector<Arrow>::iterator icurr=all_the_arrows.begin(); icurr!=all_the_arrows.end(); ++icurr)
       {
        // ...Clear previous 'in-range' arrows container, and then...
        icurr->clear_inrange_arrows(all_the_arrows.size());
        // ...Add the other arrows in range
        for(auto iother=all_the_arrows.begin(); iother!=icurr; ++iother)
            if( icurr->is_inrange_of(*iother) ) icurr->add_inrange_arrow(*iother);
        for(auto iother=icurr+1; iother!=all_the_arrows.end(); ++iother)
            if( icurr->is_inrange_of(*iother) ) icurr->add_inrange_arrow(*iother);
       }
};

然后我会考虑这个预先计算是否真的有必要,并从 Arrow 中删除 m_inrange 并将其放在本地需要此信息的地方。