C 循环将向量写入另一个

c++ loop writing a vector to another one

本文关键字:另一个 向量 循环      更新时间:2023-10-16

i具有大小n的向量V。我想以x的第一个元素为v的第一个元素,将此向量重写为另一个向量X,然后x的第二个元素将是v的最后一个元素,然后是v的第二个元素,然后是v的第二个元素,然后在最后一个元素之前进行v的元素。有智能循环可以做到吗?预先感谢!

对于那些对描述感到困惑的人,它实际上是在要求一代:

X = { V[0], V[n-1], V[1], V[n-2], V[2], .... }

为了简单,可读性等,我会做类似的事情:

// split vector (assumes size is even!)
for( i=0; i<(V.size()/2); i++){
   X.push_back(V[i*2]);
   Y.push_back(V[i*2+1]);
}
// copy reversed Y onto X
for( i=Y.size()-1; i>=0; i--)
   X.push_back(Y[i]);

我认为您明白了。

您可以尝试此代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
// your code goes here
vector<int> vec;
for(int i = 0; i < 10; i++)
    vec.push_back(i);
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
vector<int> second;
int length = vec.size();
for(int j = 0; j < length/2; j++)
{
    second.push_back(vec[j]);
    second.push_back(vec[length - j - 1]);
}
if(length % 2 == 1)
    second.push_back(vec[length/2]);
copy(second.begin(), second.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
return 0;
}

OUTPUS是:

0 1 2 3 4 5 6 7 8 9 
0 9 1 8 2 7 3 6 4 5 

在问题编辑后,很明显您可以(对于vector v)

这样做
// function to interleave ranges, you'll see the usage later
template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator interleave(InputIterator1 first1, InputIterator1 last1,
                        InputIterator2 first2, InputIterator2 last2,
                        OutputIterator result)
{
  while (first1 != last1 || first2 != last2) 
  {
    if (first1==last1) return std::copy(first2,last2,result);
    if (first2==last2) return std::copy(first1,last1,result);
    *result++ = *first1++;
    *result++ = *first2++;
  }
}
int main() // example
{
    std::vector<int> v;
    // fill v with elements
    std::vector<int> result; // this is not an "in place solution"
    interleave(v.begin(), v.end(), v.rbegin(), v.rend(), back_inserter(result));
    // result holds the answer - keep that or assign it back to v
}

这是用例