c ++遍历字符串向量

时间:2016-10-25 08:17:36

标签: c++ vector watcom

所以我最近发现了地图和矢量的使用,但是,我试图想办法循环包含字符串的矢量。

这是我尝试过的:

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

5 个答案:

答案 0 :(得分:8)

添加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;
}

答案 1 :(得分:0)

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

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

你明显有一个名为&#34; stdio&#34;在您尚未向我们展示的包含路径中。

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

顺便提一下,请注意using namespace should be avoided

答案 2 :(得分:0)

来自Open Watcom V2 Fork上的C++ Library Status page - Wiki:

  

&LT;串GT;

     

大部分都是完整的。虽然没有I / O操作符,但所有其他成员函数和字符串操作都可用。

解决方法(除了实现<<运算符之外)会询问字符串实例的C字符串:

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

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

答案 3 :(得分:0)

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

答案 4 :(得分:-2)

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

而不是:

char *someString="Blah blah blah";

我改为将其替换为:

string someString="Blah blah blah";

这种方式更有效,更容易。

相关问题