Dhivya Iyer
Dhivya Iyer

Reputation: 19

How to use for each loop for std::vector<std::string>>?

I'm trying to use a for each loop to iterate through a vector of strings, but I keep getting an error that says: expected initializer before ':' token. This is my code:

#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++;
}

I've also tried:

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++;
}

but I'm getting the same error. What am I doing wrong?

Upvotes: 1

Views: 602

Answers (1)

Chirag Shah
Chirag Shah

Reputation: 97

Seems like you are missing int main() Check this out, this works fine.

#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;
}

Upvotes: 1

Related Questions