c 遍历字符串向量

新手上路,请多包涵

所以我最近发现了 map 和 vector 的使用,但是,我很难找到一种方法来循环遍历包含字符串的向量。

这是我尝试过的:

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

当我尝试编译它时,我收到了这个错误:

 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

我用 map 尝试了同样的方法,它奏效了。唯一的区别是我将 cout 行更改为:

 cout<<t->first<<" => "<<t->last<<endl;

原文由 Jason Lee 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答
#include <iostream>
#include <vector>
#include <string>

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

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

   return 0;
}

或者使用 C++11(或更高版本):

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

typedef std::vector<std::string> STRVEC;

int main()
{
    STRVEC data = {"Hello World!", "Goodbye World!"};

    for (auto &s: data) {
        std::cout << s << std::endl;
    }

    return 0;
}

原文由 Scott Deagan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏