代码之家  ›  专栏  ›  技术社区  ›  KorbenDose

按相反顺序插入矢量

  •  0
  • KorbenDose  · 技术社区  · 6 年前

    假设我有两个相同大小的向量(父向量)填充了一些值。在这两个向量中,我想创建两个大小相同的新向量(子向量)。为此,我在指定的职位上裁减了父母,并按照以下方案填补了孩子的空缺:

    Parent 1:
    {1,  2,  3,  4,  5}
          ^cut
    Parent 2:
    {6,  7,  8,  9,  0}
              ^cut
    
    Child 1:
    {3,  4,  5,  0,  9}
    Child 2:
    {2,  1,  6,  7,  8}
    

    更多 细节 ,我在位置处切割父1 k 和父母2的位置 n-k ,在哪里 n 是父级2的大小。

    子级1将首先填充父级1的第二部分。之后,父级2的第二部分将以相反的顺序附加到子级1。子项2将以相反的顺序用父项1的第一部分开头。之后,父级2的第一部分将按前向顺序附加到子级2。

    现在,向前插入部件不是问题。向后插入是我无法工作的。

    /* Set iterators at the cutting position */
    int cut = 2;
    auto cut1 = std::begin(parent1);
    auto cut2 = std::end(parent2);
    std::advance(cut1, cut);
    std::advance(cut2, -cut);
    
    /* Fill child1 with second part of parent1 */
    child1.insert(child1.end(), cut1, std::end(parent1));
    /* Add second part of parent2 in reverse order to child1 */
    // ?
    /* Fill child2 with first part of parent1 in reverse order */
    // ?
    /* Add first part of parent2 to child2 */
    child2.insert(child2.end(), std::begin(parent2), cut2);
    

    我在看 std::back_inserter std::reverse_iterator 但我不知道他们如何合作,最优雅的方式是什么。

    我也发现了 this this 这两个问题并不完全相同,但似乎都表明,我可能需要使用简单的for循环。由于这两个问题都已经过时了,有没有一个好的方法来实现标准算法所要求的行为?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Thomas Sablik    6 年前

    您可以使用反向迭代器迭代父代,例如:

    #include <iostream>
    #include <vector>
    
    int main() {
      std::vector<int> parent1{1, 2, 3, 4, 5};
      std::vector<int> parent2{6, 7, 8, 9, 0};
    
      std::vector<int> child1;
      std::vector<int> child2;
    
      int cut = 2;
      {
        auto cut1 = std::begin(parent1); // set cut1 to element 1
        auto cut2 = parent2.rbegin(); // set cut2 to element 0 (reverse)
        std::advance(cut1, cut); // iterate cut1 to element 3
        std::advance(cut2, cut); // iterate cut2 to element 8 (reverse)
    
        child1.insert(child1.end(), cut1, std::end(parent1)); // copy elements 3, 4 ,5
        child1.insert(child1.end(), parent2.rbegin(), cut2); // copy elements 0, 9 (reverse)
      }
      {
        auto cut1 = parent1.rbegin(); // set cut1 to element 5 (reverse)
        auto cut2 = parent2.begin(); // set cut2 to element 6
        std::advance(cut1, parent1.size() - cut); // iterate cut1 to element 2 (reverse)
        std::advance(cut2, parent2.size() - cut); // iterate cut2 to element 9
    
        child2.insert(child2.end(), cut1, parent1.rend()); // copy elements 2, 1 (reverse)
        child2.insert(child2.end(), parent2.begin(), cut2); // copy elements 6, 7, 8
      }
      for (const auto& el : child1) {
        std::cout << el << " ";
      }
      std::cout << std::endl;
      for (const auto& el : child2) {
        std::cout << el << " ";
      }
      std::cout << std::endl;
      return 0;
    }
    

    因为C++ 14你可以使用 std::rbegin(parent2) 而不是 parent2.rbegin() .