繁体   English   中英

从列表中的字符串迭代器获取int dat <struct> 数组

[英]get int dat from string iterator, within a list<struct> of array

这是我遇到的问题的作业,给定字符串行,需要存储到数组列表中

这是我声明数组列表的方式

list<terms> poly[100];

这是我的结构数据类型

typedef struct Node*terms;
struct Node
{
    int expo;       //exponent
    int coef;       //coefficient
}

鉴于:

string line = "123456"

我需要一次获取前两个字符并存储到struct(在这种情况下为术语)数据类型,因此我将“ 1”保存为令牌,将“ 2”保存为token2。 另外,我需要将它们设置为int数据类型,以便以后进行计算。 将它们保存为新术语后,它将再次循环并读取“ 3”和“ 4”,将其转换并再次保存,依此类推。

我尝试使用stringstream进行转换,但它给了我invalid conversion from char' to const char*

for ( string::iterator it=line.begin(); it!=line.end(); it++){

    int token, token2;

    //change data type from string to int
    stringstream ss;
    ss<<*it;
    ss >>token;

    stringstream ss;
    ss<<*it+1;
    ss >>token2;

    //create a new struct for current line
    struct Node* p = (struct Node*) malloc(sizeof(struct Node));
    p->coef = token;
    p->expo = token2;
    poly[0].push_back(p);
}

例如,您可以使用普通循环。

std::pair<int, int> p;

for ( std::string::size_type i = 0; i < line.size(); i++ )
{
   if ( i & 1 == 0 )
   {
      p.first = line[i] - '0';
   }
   else
   {
      p.second = line[i] - '0';
      poly[0].push_back( new Node { p.first, p.second } );
   }
}

只是不清楚为什么将列表定义为std::list<Node *>而不是std::list<Node>您可以简单地编写

      poly[0].push_back( { p.first, p.second } );

暂无
暂无

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

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