[英]Passing std::vector<std::string> as array of C-style strings (char**)
[英]Cannot push C style strings into std::vector
我正在嘗試將一些const char*
推入向量,但是在執行我想填充它的操作后,向量仍未填充。
這是我的嘗試,dict是我的命令行參數。
測試文件
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream dict;
size_t dict_size;
dict.open(argv[1]); // Dictionary
vector<const char*> dictionary;
string line;
getline(dict, line);
while(!dict.fail()) {
dictionary.push_back(line.c_str());
getline(dict, line);
}
dict_size = dictionary.size();
for(int i = 0; i < dict_size; i++)
cout << "dictionary[" << i << "] is " << dictionary[i] << endl;
}
字典
Hello
World
Foo
Bar
編譯之后,我得到以下輸出:
dictionary[0] is
dictionary[1] is
dictionary[2] is
dictionary[3] is
但是,如果我將dictionary
的類型更改為vector並向后推line
而不是line.c_str()
, line.c_str()
得到預期的輸出:
dictionary[0] is Hello
dictionary[1] is World
dictionary[2] is Foo
dictionary[3] is Bar
我對C樣式字符串不是很熟悉,所以也許它與null終止有關?
請幫忙!
謝謝,erip
您正在存儲懸空指針。
std::string::c_str()
並非指向某些永久性數據副本的指針-只是想,那會被泄漏!
而是存儲std::string
。
您的代碼會調用未定義的行為,因為執行此操作后
dictionary.push_back(line.c_str());
在下一行中,該指針可能會被刪除:
getline(dict, line); // line now is a different string
您正在推入指向相同地址的字典指針,並且在最后一次迭代中,它用空字符串填充了內存區域。 如果您不關心內存泄漏,可以嘗試如下操作:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream dict;
size_t dict_size;
dict.open(argv[1]); // Dictionary
vector<char *> dictionary;
while(!dict.fail()) {
string * line = new string();
getline(dict, *line);
if(line->length()>0)
{
dictionary.push_back((char *)line->c_str());
}
}
dict_size = dictionary.size();
for(int i = 0; i < dict_size; i++)
cout << "dictionary[" << i << "] is " << dictionary[i] << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.