[英]C++/C: Convert a string to initializer list
我正在讀入一個字符串s = {1,2,3}
一些看起來像來自文本文件的初始化列表的東西。
我怎樣才能在沒有硬編碼的情況下進行像int a[3]={1,2,3}
這樣的賦值,使用像int a[3]=s;
這樣的東西int a[3]=s;
?
正如評論中所說,在 C++ 中執行此類操作的唯一方法是手動編寫解析器。 使用std::vector
的示例(由於長度可變性,您應該特別使用)可能如下所示:
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
std::vector<int> parse(const std::string& str){
if(str.front() != '{' || str.back() != '}'){
throw std::invalid_argument("vectors must be enclosed between braces");
}
std::vector<int> result;
result.reserve(std::count(str.begin(), str.end(),',')+1); // this pays off for really big vectors
std::stringstream stream(str.substr(1,str.size()-2));
std::string element;
while(getline(stream,element,',')){
result.push_back(std::stoi(element));
}
return result;
}
如果性能不是那么重要,那么應該這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.