c++ - C++ 错误为什么这个向量没有输出?
问题描述
我正在尝试输出路径向量,但它不会输出...
int main (){
vector<string> path; {"John", "Dave", "Peter", "Charlie", "Michael";};
sort(path.begin(), path.end());
cout<<path[5]<<endl;
}
我想看看
查理 戴夫 约翰 迈克尔 彼得
解决方案
分号太多,试试这个语法
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
推荐阅读
- javascript - 有没有办法在使用 JavaScript 创建 Trello 卡时获取它的 ID?
- optimization - 研讨会调度问题建模 - Julia
- qt - 从 QAbstractItemModel 或 QAbstractListModel 创建树型模型
- c# - TcpClient 如何改进原始套接字?
- reactjs - 在输入前三个字符时限制选项加载(react-select)以加快响应时间
- java - 模拟点击后如何使按钮颜色恢复正常
- bash - 有没有办法知道 `script` 命令是否在当前 bash 会话中运行?
- mongodb - Mongoose 在数组中查找子文档
- powerbi - PowerBI 中的 R 机器学习
- c# - 如何使用 Microsoft Graph api 从 azure 活动目录中获取所有用户属性