簡體   English   中英

在std :: vector中插入迭代器范圍

[英]Inserting iterator range in std::vector

我有一個多重集,我正在從中得到一個范圍。 我想將此范圍添加到向量中以供以后使用,這就是我正在做的事情:

class foo
{
    public:
        int a;
        foo(int a) : a(a){}
};
class FooPointerCompare
{
    public:
        bool operator()(const foo* a, const foo* b)
        {
            return a->a < b->a;
        }
};

std::multiset<foo*, FooPointerCompare> m;
std::vector<std::multiset<foo*, FooPointerCompare>::iterator> v;
auto pair = m.equal_range(new foo(5)); //leak here, I know
v.insert(v.end(), pair.first, pair.second);

但我得到這些錯誤:

No matching constructor for initialization of 'std::__1::__tree_const_iterator<foo *, const std::__1::__tree_node<foo *, void *> *, int>'

No viable overloaded '='

當我使用簡單的for(auto it = pair.first; it != pair.second; it++) v.push_back(it); 它完美地工作。 我的vector::insert調用有什么問題?

怎么了

v.insert(v.end(), pair.first, pair.second);

相當於

for (auto it = pair.first; it != pair.second; ++ it)
    v.push_back(*it);
//              ^

這與您的意圖不同。 我認為沒有任何標准算法可以執行您想要的操作。 最好只寫出for循環。

vector::insert期望迭代器指向要插入向量中的值。

由於您有一個迭代器向量,因此必須在迭代器上傳遞一些迭代器。 但是,您要傳遞的東西會迭代多集中的元素。

因此,此操作失敗的原因與您無法執行操作的原因相同:

std::vector<char*> v;
char foo[10];
v.insert(v.end(), foo, foo+10);

要么:

std::vector<int> v;
v.insert(v.end(), 0, 10);

解決這三個問題的一種方法是boost::counting_iterator 在您的情況下:

v.insert(v.end(),
    boost::make_counting_iterator(pair.first), 
    boost::make_counting_iterator(pair.second)
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM