繁体   English   中英

c ++ 遍历字符串向量

[英]c++ iterate through a vector of strings

所以我最近发现了地图和向量的使用,但是,我在尝试找到一种方法来遍历包含字符串的向量时遇到了麻烦。

这是我尝试过的:

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

添加iostream头文件并将stdio更改为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;
}

C++ 库状态页面上的Open Watcom V2 Fork -Wiki :

<字符串>

大部分完成。 尽管没有 I/O 运算符,但所有其他成员函数和字符串操作都可用。

一种解决方法(除了实现<<运算符)将询问 C 字符串的字符串实例:

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

这当然只有在字符串不包含零字节值时才有效。

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

当我编译你的代码时,我得到:

40234801.cpp:3:17: fatal error: stdio: No such file or directory
 #include <stdio>
                 ^

您的包含路径中显然有一个名为“ stdio ”的标题,但您没有向我们展示。

如果您将该行更改为标准#include <iostream> ,那么唯一报告的错误是您编写了void main()而不是int main() 修复它,它将构建并运行。

顺便说一句,还要注意应避免using namespace

我找到了解决我自己问题的方法。 我没有使用 c_str,而是使用 std::string 并切换到使用 G++ 编译器而不是 Open Watcom

而不是:

char *someString="Blah blah blah";

我改为将其替换为:

string someString="Blah blah blah";

这种方式效率更高,也更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM