反转不带反转函数的字符串向量
Reversing a vector of strings without the reverse function
当前正在尝试获取要反向打印的名称(字符串(向量。反向功能将不会使用,因此将"手动完成"。到目前为止,用我的方法,矢量向前打印得很好,但当涉及到向后时,它能够向后打印前4个字符串,但随后又返回到向前打印其余字符串。一直坐在上面,就是不知道怎么修。谢谢。
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> names { "Jeff", "Jim", "Jerry", "Lisa", "Terry", "Tim", "Tiff"};
std::cout << "This is the vector printing forwardsn";
for (int i = 0; i < names.size(); i++)
{
std::cout << names[i] << std::endl;
}
std::cout << "This is the vector printing backwardsn";
for (int i = 0, j = names.size() - 1; i < names.size(); i++, j--)
{
std::string temp = names[i];
names[i] = names[j];
names[j] = temp;
std::cout << names[i] << std::endl;
}
}
这是因为每个元素要交换两次。
对于大小为4的矢量:交换操作:
0 3
1 2
2 1
3 0
在向量的一半大小上循环
for (int i = 0, j = names.size() - 1; i < names.size()/2; i++, j--)
{
std::string temp = names[i];
names[i] = names[j];
names[j] = temp;
}
使用另一个循环打印矢量。
for (int i = 0; i < names.size(); i++)
{
cout<<names[i]<<endl;
}
C++的最佳实践是不编写原始循环。
尽管如此,这里有一个如何在索引的帮助下实现它的版本。
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> names{"Jeff", "Jim", "Jerry", "Lisa",
"Terry", "Tim", "Tiff"};
std::cout << "This is the vector printing forwardsn";
for (int i = 0; i < names.size(); i++) {
std::cout << names[i] << std::endl;
}
std::cout << "This is the vector printing backwardsn";
for (int i = names.size() - 1; i >= 0; i--) {
std::cout << names[i] << std::endl;
}
}
您必须不断交换值,直到向量大小的中间。
cout << "This is the vector printing backwardsn";
for (int i = 0, j = names.size() - 1; i < names.size(); i++, j--)
{
if(i < names.size()/2)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
cout << names[i] << endl;
}
对容器进行前后迭代的最简单方法是使用反向迭代器。这可以通过std::for_each((函数来完成。(前向循环也可以使用基于的范围来完成(
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::string> names { "Jeff", "Jim", "Jerry", "Lisa", "Terry", "Tim", "Tiff"};
std::cout << "This is the vector printing forwardsn";
std::for_each(names.begin(), names.end(), [](const std::string& name)
{
std::cout << name << std::endl;
});
std::cout << "This is the vector printing backwardsn";
std::for_each(names.rbegin(), names.rend(), [](const std::string& name)
{
std::cout << name << std::endl;
});
}
如果您计划手动反转容器,那么您最多可以交换容器的一半,如其他答案中所述。您也可以反向迭代原始容器,复制到一个新容器,并用新容器替换原始容器,但这已经接近于使用std::reverse((函数,而且可能更慢。
std::copy(names.rbegin(), names.rend(), std::back_inserter(newNames));
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 在将字符串放入字符串向量时遇到问题?
- 如何从字符串向量构造对象并避免复制?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 将字符串向量中的字符串放入主字符串中
- 如何在 c++ 中从字符串向量中读取
- 用字符串的向量分配字符串向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- C++ 中字符串向量的索引
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何从输入中获取字符串向量?
- 使用 C++-17,如何从字符串向量填充元组
- 对于循环增量器不能用作字符串向量的索引
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 如何从字符串向量中选择第 n 个位置?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 反转不带反转函数的字符串向量
- 如何在字符串向量中指向const int
- 如何在字符串向量中找到某个值