如何自我复制矢量?

时间:2013-02-08 21:00:03

标签: c++ vector stl

假设我有vector<string>包含“a”和“b”,我想复制自己2次,以便矢量现在包含“a”,“b”,“a”,“b”, “a”,“b”

比使用forpush_back更好的方法是什么?

4 个答案:

答案 0 :(得分:4)

我最初的想法:

myvec.reserve(myvec.size()*3);  //reserve not only speeds things upt it also protects us ftom iterator invalidation
vector<string>::iterator it = myvec.end();    //we ant to add two times the origional onto the end so we save the end of the origional end
myvec.insert(myvec.end(), myvec.begin(), it);
myvec.insert(myvec.end(), myvec.begin(), it);
感谢Emilio Garavaglia首先指出了这方面的问题,请看这里出现问题的原因很多:Does std::vector::insert() invalidate iterators if the vector has enough room (created through reserve)?

第二次尝试:

std::size_t size = myvec.size();
myvec.resize(size*3);  //resize must protects us from iterator invalidation
vector<string>::iterator it = myvec.begin()+size;
std::copy(myvec.begin(),it,it);
std::copy(myvec.begin(),it,it+size);

因为没有实现将实现std :: string,而默认构造函数在堆上分配一些内容,这应该会导致更少的堆访问,因此比其他示例更快。

另一个堆访问最小化是将矢量复制到另一个插入它然后移入原件,我偷走了Emilio Garavaglia代码并将其拉长了:

{
vector<string> m = { "a", "b" };
auto n = m; // keep initial value safe
m.reserve(3 * m.size()); // preallocate, to avoid consecutive allocations
m.insert(m.end, n.begin(), n.end());
std::for_each(n.begin(),n.end(),[&n](std::string &in){n.emplace_back(std::move(in));});
}

答案 1 :(得分:2)

vector<string> m = { "a", "b" };

auto n = m; // keep initial value safe

m.reserve(3 * m.size()); // preallocate, to avoid consecutive allocations
m.insert(m.end, n.begin(), n.end());
m.insert(m.end, n.begin(), n.end());

答案 2 :(得分:2)

我首先想到的是避免迭代器失效的问题。

{   // note: nested scope
    vector<string> temp(vec); // 1st copy
    temp.insert(temp.end(), vec.begin(), vec.end()); // 2nd copy
    temp.insert(temp.end(), vec.begin(), vec.end()); // 3rd copy
    temp.swap(vec); // swap contents before temp is destroyed
}

经过审核,我认为PorkyBrain和Emilio Garavaglia的回答可能更有意义。

答案 3 :(得分:1)

这是一个简单的方法:

template<typename T, typename A1, typename A2>
std::vector<T, A1> operator+( std::vector<T, A1> left, std::vector<T, A2> const& right ) {
  left.insert( left.end(), right.begin(), right.end() );
  return left;
}


int main() {
  std::vector<string> m = { "a", "b" );

  m = m + m + m;
}

但正如@ChristianAmmer所指出的那样,operator+上覆盖std::vector是不明确的。这是错误的。

所以你可以编写一个完整的中缀命名运算符语法,并使用C ++的魔力将其嵌入到C ++语言中,以消除这种模糊性。有点像这样:

#include <utility>

template<typename Operation, short op>
struct InfixOp {
  Operation* self() { return static_cast<Operation*>(this); }
  Operation const* self() const { return static_cast<Operation const*>(this); }
};

template<typename first_type, typename Infix, short op>
struct PartialForm {
  Infix const* infix;

  first_type a;

  template<typename T>
  PartialForm(T&& first, Infix const* i):infix(i), a(std::forward<T>(first)) {}
};

#define OVERRIDE_OPERATORS(OP, CODE) \
template<\
  typename Left,\
  typename Operation\
>\
PartialForm<typename std::remove_reference<Left>::type, Operation, CODE> operator OP( Left&& left, InfixOp<Operation, CODE> const& op ) {\
  return PartialForm<typename std::remove_reference<Left>::type, Operation, CODE>( std::forward<Left>(left), op.self() );\
}\
\
template<\
  typename Right,\
  typename First,\
  typename Operation\
>\
auto operator OP( PartialForm<First, Operation, CODE>&& left, Right&& right )\
  ->decltype( (*left.infix)( std::move( left.a ), std::forward<Right>(right)) )\
{\
  return (*left.infix)( std::move( left.a ), std::forward<Right>(right) );\
}

OVERRIDE_OPERATORS(+, '+')
OVERRIDE_OPERATORS(*, '*')
OVERRIDE_OPERATORS(%, '%')
OVERRIDE_OPERATORS(^, '^')
OVERRIDE_OPERATORS(/, '/')
OVERRIDE_OPERATORS(==, '=')
OVERRIDE_OPERATORS(<, '<')
OVERRIDE_OPERATORS(>, '>')
OVERRIDE_OPERATORS(&, '&')
OVERRIDE_OPERATORS(|, '|')
//OVERRIDE_OPERATORS(!=, '!=')
//OVERRIDE_OPERATORS(<=, '<=')
//OVERRIDE_OPERATORS(>=, '>=')


template<typename Functor, char... ops>
struct Infix:InfixOp<Infix<Functor, ops...>, ops>...
{
  Functor f;
  template<typename F>
  explicit Infix(F&& f_in):f(std::forward<F>(f_in)) {}
  Infix(Infix<Functor, ops...> const& o):f(o.f) {}
  Infix(Infix<Functor, ops...>&& o):f(std::move(o.f)) {}
  Infix(Infix<Functor, ops...>& o):f(o.f) {}
  template<typename L, typename R>
  auto operator()( L&& left, R&& right ) const
    -> decltype( f(std::forward<L>(left), std::forward<R>(right)))
  {
    return f(std::forward<L>(left), std::forward<R>(right));
  }
};

template<char... ops, typename Functor>
Infix<Functor, ops...> make_infix( Functor&& f )
{
  return Infix<Functor, ops...>(std::forward<Functor>(f));
}

#include <vector>

struct append_vectors {
  template<typename T>
  std::vector<T> operator()(std::vector<T> left, std::vector<T>const& right) const {
    left.insert(left.end(), right.begin(), right.end());
    return std::move(left);
  }
};

struct sum_elements {
  template<typename T>
  std::vector<T> operator()(std::vector<T> left, std::vector<T>const& right) const {
    for(auto it = left.begin(), it2 = right.begin(); it != left.end() && it2 != right.end(); ++it, ++it2) {
      *it = *it + *it2;
    }
    return left;
  }
};
struct prod_elements {
  template<typename T>
  std::vector<T> operator()(std::vector<T> left, std::vector<T>const& right) const {
    for(auto it = left.begin(), it2 = right.begin(); it != left.end() && it2 != right.end(); ++it, ++it2) {
      *it = *it * *it2;
    }
    return left;
  }
};

#include <iostream>

int main() {
  auto append = make_infix<'+'>(append_vectors());
  auto sum = make_infix<'+'>(sum_elements());
  auto prod = make_infix<'*'>(prod_elements());

  std::vector<int> a = {1,2,3};
  a = a +append+ a +append+ a;
  a = a +sum+ a;
  a = a *prod* a;

  std::cout << a.size() << "\n";
  for (auto&& x:a) {
    std::cout << x << ",";
  }
  std::cout << "\n";
}

在您使用它时具有清晰的优势(我的意思是,a = a +append+ a非常清楚它打算做什么),代价是有点难以理解它是如何工作的,以及这个简单的问题有点冗长。

但至少这种歧义消失了,这是件好事,对吗?