将 vector<vector<int>> 的最后一个元素移动到开头
Move last element of vector<vector<int>> to beginning
我需要将 vector<vector<int>>
的最后一个元素移到开头。我试过 std::rotate
,但它只适用于整数。我也试过 std::move
但我失败了。我该怎么做?提前谢谢你。
要将最后一个元素放在开头,您可以使用 std::rotate function with reverse iterators。这将执行右旋转:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
for (auto el : v) {
std::cout << el << ' ';
}
}
要交换第一个和最后一个元素,请使用 std::swap function with vector's front() and back() 引用:
std::swap(v.front(), v.back());
std::rotate
函数不依赖于类型。
我需要将 vector<vector<int>>
的最后一个元素移到开头。我试过 std::rotate
,但它只适用于整数。我也试过 std::move
但我失败了。我该怎么做?提前谢谢你。
要将最后一个元素放在开头,您可以使用 std::rotate function with reverse iterators。这将执行右旋转:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
for (auto el : v) {
std::cout << el << ' ';
}
}
要交换第一个和最后一个元素,请使用 std::swap function with vector's front() and back() 引用:
std::swap(v.front(), v.back());
std::rotate
函数不依赖于类型。