首页 > 解决方案 > C++ 错误为什么这个向量没有输出?

问题描述

我正在尝试输出路径向量,但它不会输出...

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

我想看看

查理
戴夫
约翰
迈克尔
彼得

标签: c++stringvector

解决方案


分号太多,试试这个语法

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

在此处阅读有关初始化列表语法的更多信息:https ://en.cppreference.com/w/cpp/language/list_initialization

您不需要标识符后面的分号,也不需要{}列表中的分号,而只需要语句末尾的分号。

此外,path[5]将尝试使用第六个元素,但您只尝试定义 5。

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

输出:

Peter

推荐阅读