C++ 错误 为什么这个矢量不输出?

C++ Error why isn't this vector outputting?

本文关键字:输出 错误 为什么 C++      更新时间:2023-10-16

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

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

我想看

查理 戴夫 John 迈克尔 彼得

分号太多,请尝试使用此语法

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