2

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?

  • Can you please post more detailed input-output example? You declared a vector of strings yet you want to store letters? Of which type are `start`,`end` variables? Writing `alpahbet.end()` twice is a typo? You might want to look at [`std::back_inserter`](https://en.cppreference.com/w/cpp/iterator/back_inserter) as STL functions do not resize containers. – Quimby Jul 08 '20 at 14:43

2 Answers2

6

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,

stribor14
  • 340
  • 2
  • 9
1

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)

Andrew
  • 148
  • 6
  • 1
    You might as well use `'a'` instead of 97, better to read. – Lukas-T Jul 08 '20 at 14:44
  • Yeah, I actually haven't thought of that, I prefer to use numbers when adding characters (or even hex rather then decimal, but decimal is better for readability), but I'll update it – Andrew Jul 08 '20 at 14:46
  • 2
    OP already knows how to get a vector containing the letters, the question is how to add "start" and "end" to that – 463035818_is_not_an_ai Jul 08 '20 at 14:50