[英]using istringstream to tokenize std::string to std::map
I have a vector that contains data like: 我有一个包含如下数据的向量:
std::vector<std::string> v;
v[0] = "first:tom";
v[1] = "last:jones";
and I want to iterate through the vector and parse at :
and put results in a std::map
我想遍历向量并在
:
解析并将结果放入std::map
std::vector<std::string> v;
std::map<std::string, std::string> m;
std::pair<std::string, std::string> p;
for(int i = 0; i < v.size(); i++)
{
std::cout << v[i] << std::endl;
std::istringstream oss(v[i]);
std::string token;
while(getline(oss, token, ':'))
{
m.insert(std::pair<std::string, std::string>("", ""));
}
}
I am stuck on insertion to the std::map
because I dont see how the parse gives me both pieces that I can insert into the map. 我无法插入到
std::map
因为我看不到解析如何为我提供了我可以插入地图中的两个片段。
It isn't v[i] in both. 两者都不是v [i]。
I want: 我想要:
m.insert(std::pair<std::string, std::string>("first", "tom"));
m.insert(std::pair<std::string, std::string>("last", "jones"));
Can anyone explain my difficulty? 谁能解释我的困难?
Try 尝试
std::vector<std::string> v;
std::map<std::string, std::string> m;
for(int i = 0; i < v.size(); i++)
{
std::cout << v[i] << std::endl;
size_t sepPosition = v[i].find (':');
//error handling
std::string tokenA = v[i].substr(0, sepPosition);
std::string tokenB = v[i].substr(sepPosition + 1)
m.insert(std::pair<std::string, std::string>(std::move(tokenA), std::move(tokenB)));
}
Something like this: 像这样:
std::vector<std::string> v;
std::map<std::string, std::string> m;
std::pair<std::string, std::string> p;
for(int i = 0; i < v.size(); i++)
{
std::cout << v[i] << std::endl;
std::istringstream oss(v[i]);
std::string key;
std::string value;
while(getline(oss, key, ':') && getline(oss, value))
{
m.insert(std::pair<std::string, std::string>(key, value));
}
}
Use std::transform : 使用std :: transform :
transform(v.begin(), v.end(), inserter(m, m.begin()), chopKeyValue);
Where chopKeyValue
is: 其中
chopKeyValue
是:
pair<string, string> chopKeyValue(const string& keyValue) {
string::size_type colon = keyValue.find(':');
return make_pair(keyValue.substr(0, colon), keyValue.substr(colon+1));
}
And yet another option (C++11): 还有另一种选择(C ++ 11):
std::vector<std::string> v = { "first:tom", "last:jones" };
std::map<std::string,std::string> m;
for (std::string const & s : v) {
auto i = s.find(':');
m[s.substr(0,i)] = s.substr(i + 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.