简体   繁体   English

C++/C:将字符串转换为初始化列表

[英]C++/C: Convert a string to initializer list

I'm reading into a string s = {1,2,3} something that looks like an initializer list from a text file.我正在读入一个字符串s = {1,2,3}一些看起来像来自文本文件的初始化列表的东西。

How can I do an assignment like int a[3]={1,2,3} without hardcoding it, using something like int a[3]=s;我怎样才能在没有硬编码的情况下进行像int a[3]={1,2,3}这样的赋值,使用像int a[3]=s;这样的东西int a[3]=s; ? ?

As it's been said in the comments, the only way to do something like this in C++ is to manually write a parser.正如评论中所说,在 C++ 中执行此类操作的唯一方法是手动编写解析器。 An example using std::vector (that you should use specially because of the lenght variability) could be the following:使用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;
}

If performance is not that important, this should do.如果性能不是那么重要,那么应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM