开发者

+= on a vector without boost

Is there any way to use the += operator with a vector without using boost or using a derivated class?

Eg.

somevector += 1, 2, 3, 4, 5, 6, 7;

would actuall开发者_如何学Pythony be

somevector.push_back(1);
somevector.push_back(2);
somevector.push_back(3);
etc.


With a little ugly operator overloading, this isn't too difficult to accomplish. This solution could easily be made more generic, but it should serve as an adequate example.

#include <vector>

Your desired syntax uses two operators: the += operator and the , operator. First, we need to create a wrapper class that allows us to apply the , operator to push an element onto the back of a vector:

template <typename T>
struct push_back_wrapper
{
    explicit push_back_wrapper(std::vector<T>& v) : v_(&v) { }

    push_back_wrapper& operator,(const T& x)
    {
        v_->push_back(x);
        return *this;
    }

    std::vector<T>* v_;
};

Then, in order to use this in conjunction with += on a vector, we overload the += operator for a vector. We return a push_back_wrapper instance so that we can chain push backs with the comma operator:

template <typename T, typename U>
push_back_wrapper<T> operator+=(std::vector<T>& v, const U& x)
{
    v.push_back(x);
    return push_back_wrapper<T>(v);
}

Now we can write the code you have in your example:

int main()
{
    std::vector<int> v;
    v += 1, 2, 3, 4, 5, 6, 7;
}

The v += 1 will call our operator+= overload, which will return an instance of the push_back_wrapper. The comma operator is then applied for each of the subsequent elements in the "list."


Not with syntax like that, no. But you could do something like this:

int tmparray[] = {1, 2, 3, 4, 5, 6, 7};

somevector.insert(somevector.end(), 
                  tmparray, 
                  tmparray + (sizeof(tmparray) / sizeof(tmparray[0])));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜