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

Viewed 307

I am trying to make a vector to look like this: alphabet= {start,A,B,C,D,E,F,G,H,I,J,K,etc..,end}

The alphabet doesn't go from A to Z, the user inputs the values. So if user inputs 5, I want the vector to be: {start,A,B,C,D,E,end}

I tried using iota but I don't know how to push the "start" and "end" at the extremities of the vector

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

How to push the start and end values?

2 Answers

For the first 5 letters of alphabet

#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<< ", ";
}

Output of this block of code is: start, A, B, C, D, E, end,

I think what you want is something like this:

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

This will work, because chars use ASCII encoding, and "A" has an ASCII value of 97, and it increases from there, so 65 + 0 = 'A', 65 + 1 = 'B', and so on. (Of course include vector to have access to std::vector, or use a C array, as this: char* characters = malloc(numberOfLetters);

A note here: you don't need to use the number 65, you can write 'A' like this:

characters[i] = 'A' + i;

as the characters can be added, because they can be represented as numbers. (suggested by churill)

Related