反转不带反转函数的字符串向量

Reversing a vector of strings without the reverse function

本文关键字:字符串 向量 函数      更新时间:2023-10-16

当前正在尝试获取要反向打印的名称(字符串(向量。反向功能将不会使用,因此将"手动完成"。到目前为止,用我的方法,矢量向前打印得很好,但当涉及到向后时,它能够向后打印前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));