![](/img/trans.png)
[英]Checking for Item in std::vector<std::vector<std::string>> Using std::find
[英]Using std::find to find chars read from binary file and cast to a std::string in a std::vector<string> creates this inpredictible behaviour?
抱歉,標題太長了。 我不知道如何用簡短的詞來形容。
您是否願意重現我遇到的問題?
您可以使用任何wav文件進行讀取。
我試圖在這里查詢wav文件中的塊,這是代碼的簡化版本,但是我認為如果有問題,可能足以重新創建。
我使用的是Mac,並使用g++ -std=c++11
編譯。
當我運行這段代碼並且不包括std::cout << query << std::endl;
然后std::find(chunk_types.begin(), chunk_types.end(), query) != chunk_types.end()
在所有迭代中均返回0。 但是我知道二進制文件包含其中一些塊。 如果我加入這行,那么它可以正常工作,但是那也是不可預測的,可以說有時候它可以正常工作。
我有點困惑,我在這里做錯什么了嗎?
#include <fstream>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main(){
std::vector<std::string> chunk_types{
"RIFF","WAVE","JUNK","fmt ","data","bext",
"cue ","LIST","minf","elm1",
"slnt","fact","plst","labl","note",
"adtl","ltxt","file"};
std::streampos fileSize;
std::ifstream file(/* file path here */, std::ios::binary);
file.seekg(0, std::ios::beg);
char fileData[4];
for(int i{0};i<100;i+=4){ //100 is an arbitrary number
file.seekg(i);
file.read((char*) &fileData[0], 4);
std::string query(fileData);
std::cout << query << std::endl;
/* if i put this std::cout here, it works or else std::find always returns 0 */
if( std::find(chunk_types.begin(), chunk_types.end(), query) != chunk_types.end() ){
std::cout << "found " + query << std::endl;
}
}
return 0;
}
std::string query(fileData)
在fileData
上使用strlen
查找其終止0,但未找到1,因為fileData
不以0終止導致堆棧堆棧並導致SIGSEGV
。
同樣, file.read
可以讀取的符號少於預期的符號,必須使用gcount
提取上次讀取的實際字符數:
解決方法:
file.read(fileData, sizeof fileData);
auto len = file.gcount();
std::string query(fileData, len);
一種更有效的解決方案是直接讀入std::string
並繼續重用它以避免內存分配(如果沒有短字符串優化)並復制:
std::string query;
// ...
constexpr int LENGTH = 4;
query.resize(LENGTH);
file.read(&query[0], LENGTH);
query.resize(file.gcount());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.