簡體   English   中英

將字符串向量轉換為緩沖區

[英]Convert string vector to buffer

我有一個字符串向量,其中包含一些大於500的字符串。我正在使用openssl函數,這些函數需要用於加密/解密的緩沖區。 假設我以這種方式使用字符串向量和緩沖區,那么就空間和時間而言,進行此轉換的最佳算法是什么。 可以假定每個字符串少於200個字符。

當前,我正在提取路徑中的每個條目,連接字符串,調用.c_str()方法,並使用strcpy從函數中提取。

void copy(vector<string>& paths, unsigned char** plainTextBuffer, size_t& p_len){
int size = paths.size();
int i = 0;
string temp = "";
for(i=0; i<size; i++){
  temp+= paths[i];
  temp+= "\n";
}
p_len = temp.length();
(*plainTextBuffer) = malloc(p_len + 1);
strcpy((*plainTextBuffer), temp.c_str());
return;
}

有內置的工具可以更好,更快地做到這一點嗎? (我已從此代碼段中排除了錯誤檢查和轉換)

編輯:

我將+1添加到了malloc中。 我要求一種從初始條件到預期輸出的最小復雜度方式。 我使用malloc是因為我使用了一個簡單的緩沖區,它比新緩沖區快。

編輯2:

多虧了一些評論,我削減了中間人的一些復制品,並提出以下建議

void copy(vector<string>& paths, unsigned char** plainTextBuffer, size_t& p_len){
    int size = paths.size(), total = 0, i = 0;
    for(i=0; i<size; i++){
      total+= paths[i].size() + 1;
    }
    p_len = total;
    (*plainTextBuffer) = malloc(p_len + 1);
    (*plainTextBuffer)[0] = '\0';
    for(i=0; i<size; i++){
      strcat((*plainTextBuffer), paths[i].c_str());
      strcat((*plainTextBuffer, "\n");
    }
    return;
}

再次,我省略了一些選角。 有沒有更有效的方式將緩沖區數據放入plainTextBuffer

string轉換為C樣式字符串的最快方法是不進行任何轉換。 首先,讓我們將std::vector<std::string>轉換為一個std::string

std::vector<std::string> v = ...;
std::string output;
for (auto& s : v) {
    output += s;
    output += '\n';
}

然后,您可以將其傳遞給:

void some_c_api(char*, size_t );
void some_const_c_api(const char*, size_t);

some_c_api(&output[0], output.size());
some_const_c_api(output.c_str(), output.size());

重復追加到字符串中將導致該字符串反復重新分配內存,並將其內容改組到新的較大空間中。 字符串流具有更大的創建成本,但它的添加速度比std :: string快得多,因此,除了將其附加到循環中的字符串之外,還可以將其附加到字符串流中:

stringstream temp;
for(size_t i=0; i<paths.size(); i++){
    temp << paths[i] << endl;
}
const std::string& tmp = temp.str();

然后就像使用先前的臨時字符串一樣使用tmp。 最好獲得對temp.str()的常量引用,因為它不會復制str()創建的臨時文件的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM