c++ - 如何为std::vector <std::string >>的每个循环使用?

标签 c++

我正在尝试对每个循环使用a来遍历字符串 vector ,但是我不断收到错误消息:expected initializer before ':' token
这是我的代码:

#include <string>
#include <vector>
#include <iostream>
std::vector<std::string> tokens {"Dog","Ship","Coffee","Laptop","Shoe","McDonald's Cup","Airplane","Cellphone"};
int token_num=1;
for (std:string& token : tokens) {
     std::cout<<token_num<<": "<<token<<"\n";
     token_num++;
}

我也尝试过:
std::vector<std::string> tokens {"Dog","Ship","Coffee","Laptop","Shoe","McDonald's Cup","Airplane","Cellphone"};
int token_num=1;
for (const auto& token : tokens) {
     std::cout<<token_num<<": "<<token<<"\n";
     token_num++;
}

但是我遇到了同样的错误。
我究竟做错了什么?

最佳答案

好像您缺少int main()检查一下,这很好。

#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<string> tokens {"Dog","Ship","Coffee","Laptop","Shoe","McDonald's Cup","Airplane","Cellphone"};
    int token_num=1;
    for (string& token : tokens) {
         cout<<token_num<<": "<<token<<"\n";
         token_num++;
    }


    token_num=1;
    for (const auto& token : tokens) {
        cout<<token_num<<": "<<token<<"\n";
        token_num++;
    }
    return 0;
}

关于c++ - 如何为std::vector <std::string >>的每个循环使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61312401/

相关文章:

c++ - 调用与方法同名的函数

c++ - 我怎样才能从 MFC 中的 HTTP 服务器获得响应?

c++ - 从 BGL 图中提取邻接矩阵

c++ - 正在发送数据报,但未收到 + 其他问题

c++ - 在QT中使用鼠标捕获全局键盘

c++ - 怎么做自动阵列检测?

c++ - 为什么 STL::list 复制添加到列表中的元素?

c++ - 我可以在 gdb pretty-print 中直接调用程序的 `operator[]` 吗?

C++判断一个变量是引用还是指针

c++ - 使用 boost 进程编译一个简单的应用程序会生成错误