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

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

我正在尝试制作一个如下所示的矢量: alphabet= {开始,A,B,C,D,E,F,G,H,I,J,K,etc..,end}

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

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

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

如何推送 startend 值?

我想你想要的是这样的:

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;

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

对于字母表的前 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,