您的代码有几个问题:
1) 此处循环中使用了错误的索引变量:
for (int j = 0; i < colums; j++)
2) 该std::vector::erase
函数将迭代器作为参数,而不是位置。
3) 即使你修复了 1) 中提到的循环,你也不会检查你是否在字符串的末尾。
4)您的最终输出不输出回车,使输出看起来“错误”。
给定您使用的字符串,进行适当的更改,代码可能如下所示:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void encryption(string s)
{
const int rows = 7;
const int colums = 8;
vector<vector<char>> v;
for (int i = 0; i < rows; i++)
{
vector<char>temp;
for (int j = 0; j < colums && !s.empty(); j++) // <-- Note we stop the loop if the string is empty.
{
temp.push_back(s[0]);
s.erase(s.begin()); // <-- This erases the first character
}
v.push_back(temp);
}
for (size_t i = 0; i < v.size(); i++)
{
for (size_t j = 0; j < v[i].size(); j++)
cout << v[i][j];
cout << "\n"; // <-- You are missing this in your output
}
}
int main()
{
encryption("ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots");
}
输出:
ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots
鉴于此,这是非常低效的,因为您正在擦除字符串的第一个字符。没有必要为此删除一个字符。
这是一个使用 , 的替代解决方案std::vector<std::string>
,以及一个while
跟踪字符串中开始和结束迭代器的循环:
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
void encryption(std::string s)
{
const size_t columns = 8;
std::vector<std::string> v;
// start at beginning of string
auto startIter = s.begin();
// point to either 8 characters after the start, or the end of the
// string, whichever comes first
auto endIter = startIter + std::min(columns, static_cast<size_t>(std::distance(startIter, s.end())));
while (true)
{
// just push on a string using the start and end iterators
v.push_back({startIter, endIter});
// if the end iterator is at the end of the string, quit
if (endIter == s.end())
break;
// move the start to the end
startIter = endIter;
// move the end to either 8 characters after the start, or the
// end of the string, whichever comes first
endIter = startIter + std::min(columns, static_cast<size_t>(std::distance(startIter, s.end())));
}
// Output the results
for (auto& vrow : v)
std::cout << vrow << "\n";
}
int main()
{
encryption("ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots");
}
输出:
ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots