C 循环将向量写入另一个
c++ loop writing a vector to another one
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
}
这是用例
相关文章:
- 将一个向量插入另一个向量的某个位置
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 如何按另一个向量的方向调整一个向量?
- 将字符向量复制到另一个向量
- 如何将所有指针从一个向量移动到另一个向量?
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 用一个向量替换另一个向量的方法
- 如何根据另一个向量中给出的索引拆分向量?
- 按另一个向量对一个向量进行排序
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- 如何从一个向量中删除最小元素并添加到另一个向量,而第一个变为空?
- C++将 X 向量数据插入到另一个向量
- 将向量{x,y,z}插入另一个向量
- 给出一个 std::vector 对另一个向量的内存的所有权?
- 从另一个向量中搜索和找到元素的有效方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃