c++vectoriota

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


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?


Solution

  • 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,