根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢

Fill vector with alphabets depending on user input and put Start and End on the extremities

本文关键字:quot 开始 结束 并将 输入 用户 填充      更新时间:2023-10-16

我正在尝试使向量看起来像这样: alphabet= {开始,A,B,C,D,E,F,G,H,I,J,K,等等,结束}

字母表不是从 A 到 Z,而是用户输入值。 因此,如果用户输入 5,我希望向量为: {开始,A,B,C,D,E,end}

我尝试使用 iota,但我不知道如何在矢量的末端推动"开始"和"结束">

vector<string> alphabet;
iota(alphabet.start(), alphabet.end(), 'A');

如何推动startend值?

对于字母表的前 5 个字母

#include <iostream>
#include <vector>
#include <string>
#include <numeric>
int main() {
// vector needs to be allocated, +2 is for start and end
std::vector<std::string> alphabet(5+2); 
// front() gives you reference to first item
alphabet.front() = "start";
// end() gives you reference to last item
alphabet.back() = "end";
// you can use iota, but skipping the first and last item in vector
std::iota(std::next(alphabet.begin()), std::prev(alphabet.end()), 'A'); 
for (const auto& S : alphabet)
std::cout<<S<< ", ";
}

此代码块的输出为:start, A, B, C, D, E, end,

我认为你想要的是这样的东西:

int numberOfLetters;
std::cin >> numberOfLetters;
std::vector<char> characters(numberOfLetters);
for(int i = 0; i < numberOfLetters; i++)
{
characters[i] = 65 + i;
}

这将起作用,因为字符使用 ASCII 编码,而"A"的 ASCII 值为 97,并且从那里开始增加,因此 65 + 0 = 'A',65 + 1 = 'B',依此类推。(当然包括向量来访问std::vector,或者使用C数组,如:char* characters = malloc(numberOfLetters);

这里需要注意:你不需要使用数字65,你可以这样写"A":

characters[i] = 'A' + i;

因为字符可以添加,因为它们可以表示为数字。(丘里尔建议)