【问题标题】:STL Algorithms to generate and copy a vector用于生成和复制向量的 STL 算法
【发布时间】:2014-10-22 23:09:33
【问题描述】:

您能告诉我如何使用 STL 算法执行以下操作吗?

// Create a vector of 50 elements, and assign elem value same as index value
std::vector<int> a(50);
for (int i = 0; i < a.size(); i++)
{
    a[i] = i;
}

// Create another vector by copying a section of vector a
std::vector<int> b;
size_t ind = 20;
b.resize(a.size() - ind);
for (int i = 0; i < b.size(); i++)
{
    b[i] = a[i+ind];
}

基本上,我试图通过跳过 a 的第一个“ind”元素,从向量 a 创建一个新的向量 b。

【问题讨论】:

  • 最好指出哪些块可以组合以获得更好的效果。 (以及想要什么和问题的神器)
  • 提示:std::vector 有一个带有两个迭代器的构造函数。
  • @Deduplicator,根据我的编辑,基本上是 2 个块
  • @juanchopanza,知道了!这是第二个块,谢谢

标签: c++ algorithm vector stl


【解决方案1】:

我可能会这样做:

std::vector<int> a(50);

// fill a with 0..N
std::iota(a.begin(), a.end(), 0);

size_t ind = 20;

// initialize `b` from elements of `a`:    
std::vector<int> b{a.begin()+ind, a.end()};

您可以将std::copy 用于第二部分,但对于手头的情况,我更愿意像上面所做的那样从迭代器中初始化b

【讨论】:

    【解决方案2】:

    借助 boost,您也可以使用初始化来完成第一部分(请参阅 Jerry 的回答)。

    auto r = boost::irange(0,50);
    auto a = std::vector<int>(std::begin(r), std::end(r));
    

    我认为 Eric Neibler 的范围库包括这种类型的东西,我完全希望它会进入 C++17。在此之前,您必须将他的或 boost 用作第三方库。

    【讨论】:

    • 圣钼超级疯狂真棒
    • 在这种情况下 r 可以是 std::vector 以外的东西吗?
    • @user3670482:是的,在这种情况下,r 不是 std::vector&lt;int&gt;
    【解决方案3】:

    使用

    template <class InputIterator>
    vector (InputIterator first, InputIterator last,
        const allocator_type& alloc = allocator_type());
    

    构造函数如下。

    auto start = std::next(a.begin(), 20);
    std::vector<int> b(start, a.end());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多