Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ iterate through a vector of strings

Tags:

c++

vector

watcom

So I recently discovered the use of map and vectors, however, I'm having trouble of trying to figure a way to loop through a vector containing strings.

Here's what I've tried:

#include <string>
#include <vector>
#include <stdio>

using namespace std;

void main() {
    vector<string> data={"Hello World!","Goodbye World!"};

    for (vector<string>::iterator t=data.begin(); t!=data.end(); ++t) {
        cout<<*t<<endl;
    }
}

and when I try to compile it, I get this error:

cd C:\Users\Jason\Desktop\EXB\Win32
wmake -f C:\Users\Jason\Desktop\EXB\Win32\exbint.mk -h -e
wpp386 ..\Source\exbint.cpp -i="C:\WATCOM/h;C:\WATCOM/h/nt" -w4 -e25 -zq -od    -d2 -6r -bt=nt -fo=.obj -mf -xs -xr
..\Source\exbint.cpp(59): Error! E157: col(21) left expression must be integral
..\Source\exbint.cpp(59): Note! N717: col(21) left operand type is 'std::ostream watcall (lvalue)'
..\Source\exbint.cpp(59): Note! N718: col(21) right operand type is 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> (lvalue)'
Error(E42): Last command making (C:\Users\Jason\Desktop\EXB\Win32\exbint.obj) returned a bad status
Error(E02): Make execution terminated
Execution complete

I tried the same method using map and it worked. The only difference was I changed the cout line to:

cout<<t->first<<" => "<<t->last<<endl;
like image 772
Jason Lee Avatar asked Oct 25 '16 08:10

Jason Lee


People also ask

How do you iterate through a vector?

Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec.


1 Answers

Add iostream header file and change stdio to cstdio.

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

using namespace std;

int main() 
{
    vector<string> data={"Hello World!","Goodbye World!"};
    for (vector<string>::iterator t=data.begin(); t!=data.end(); ++t) 
    {
        cout<<*t<<endl;
    }
    return 0;
}
like image 193
Ishpreet Avatar answered Sep 23 '22 14:09

Ishpreet