2

我正在尝试使向量看起来像这样:Alphabet= {start,A,B,C,D,E,F,G,H,I,J,K,etc..,end}

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

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

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

如何推动startend价值观?

4

2 回答 2

6

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

于 2020-07-08T14:51:20.877 回答
1

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

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',依此类推。(当然包括 vector 以访问 std::vector,或使用 C 数组,如下所示:char* characters = malloc(numberOfLetters);

此处注意:您不需要使用数字 65,您可以这样写“A”:

characters[i] = 'A' + i;

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

于 2020-07-08T14:43:04.213 回答