[英]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.