提问者:小点点

根据用户输入使用字母填充向量,并将开始和结束放在末端


我试图使一个向量看起来像这样:Alphabet={start,a,B,C,D,E,F,G,H,I,J,K等,end}

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

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

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

如何推送开始结束值?


共2个答案

匿名用户

对于字母表的前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,从97开始增加,因此65+0=“a”,65+1=“b”,依此类推。 (当然包括vector以访问std::vector,或者使用C数组,如下所示:char*characters=malloc(numberOfLetters);

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

characters[i] = 'A' + i;

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

相关问题