[英]How to add a vector in reverse order with another vector in C++?
有一個向量vector<int>v
我想以與此向量相反的順序添加另一個向量vector<int>temp
。
例如,
v = {1, 5, 7} and
temp = {11, 9, 8}
我想以相反的順序添加 temp,即{8, 9, 11}
到向量v
。
因此, v
將是: v = {1, 5, 7, 8, 9, 11}
這是我如何做到的:
int a[] = {1, 5, 7};
vector<int>v(a,a+3);
int b[] = {11, 9, 8};
vector<int>temp(b,b+3);
for(int i=temp.size()-1;i>=0;i--)
v.push_back(temp[i]);
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<"\n";
STL 或 C++ 中是否有內置函數來執行此操作? 還是我必須手動完成?
使用反向迭代器:
std::vector<int> temp(v.rbegin(), v.rend());
或std::reverse_copy()
:
std::reverse_copy(v.begin(), v.end(), std::back_inserter(temp));
嘗試以下
v.insert( v.end(), temp.rbegin(), temp.rend() );
這是一個演示程序
#include <iostream>
#include <vector>
int main()
{
int a[] = { 1, 5, 7 };
std::vector<int> v( a, a + 3 );
int b[] = { 11, 9, 8 };
std::vector<int> temp( b, b + 3 );
v.insert( v.end(), temp.rbegin(), temp.rend() );
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
程序輸出是
1 5 7 8 9 11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.