-2

I'm trying to output the path vector but it won't output...

int main (){
    vector<string> path; {"John", "Dave", "Peter", "Charlie", "Michael";};
    sort(path.begin(), path.end());
    cout<<path[5]<<endl;
}

I want to see

Charlie 
Dave 
John 
Michael 
Peter
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Oliver
  • 13
  • 1
  • What output do you get? – David G Oct 03 '19 at 00:37
  • Exited, segmentation fault – Oliver Oct 03 '19 at 00:39
  • Your vector is empty, accessing its 5th element is UB. – Max Vollmer Oct 03 '19 at 00:39
  • `path; {` should be `path = {`. Also the semicolon after "Michael" needs to be removed. – Max Vollmer Oct 03 '19 at 00:40
  • 2
    Even after correcting the other errors, you're still attempting to access beyond the end of the vector. You have 5 elements so your maximum index value is 4. – jkb Oct 03 '19 at 00:45
  • @Oliver vector start from "0" so if you have 5 elements you can access up to index number 4 (path[0] to path[4]), also remove those excessive semicolons. – Vencat Oct 03 '19 at 00:45
  • 1
    Possible duplicate of [How to print out the contents of a vector?](https://stackoverflow.com/questions/10750057/how-to-print-out-the-contents-of-a-vector) (assuming the other bugs are fixed) – JaMiT Oct 03 '19 at 00:47

1 Answers1

4

You have too many semicolons, try this syntax instead

vector<string> path {"John", "Dave", "Peter", "Charlie", "Michael"};

Read more about initialization list syntax here: https://en.cppreference.com/w/cpp/language/list_initialization

You don't want a semicolon after the identifier, nor a semicolon in the {} list, but only one at the end of the statement.

Additionally, path[5] would be an attempt to use the sixth element, but you've only attempted to define 5.

  vector<string> path {"John", "Dave", "Peter", "Charlie", "Michael"};
  sort(path.begin(), path.end());
  cout<< path[4] <<endl;

Output:

Peter
payo
  • 4,501
  • 1
  • 24
  • 32