简体   繁体   English

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

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

This is the homework that I encounter problem, given line of string and need to store into a list of array 这是我遇到的问题的作业,给定字符串行,需要存储到数组列表中

Here is how I declare the list of array 这是我声明数组列表的方式

list<terms> poly[100];

And here is my struct data type 这是我的结构数据类型

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

Given: 鉴于:

string line = "123456"

I need to get the first two characters at a time and store to a struct(terms in this case) Data type so I save '1' as token and '2' as token2. 我需要一次获取前两个字符并存储到struct(在这种情况下为术语)数据类型,因此我将“ 1”保存为令牌,将“ 2”保存为token2。 Also I need them to be int data type for later calculation. 另外,我需要将它们设置为int数据类型,以便以后进行计算。 After saving them into new terms, it will loop again and read '3' and '4', convert them and save again, etc. 将它们保存为新术语后,它将再次循环并读取“ 3”和“ 4”,将其转换并再次保存,依此类推。

I've tried to use stringstream to convert but it gave me invalid conversion from char' to const char* 我尝试使用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);
}

For example you can use an ordinary loop. 例如,您可以使用普通循环。

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 } );
   }
}

Only it is not clear why you defined the list as std::list<Node *> instead of std::list<Node> You could write simply 只是不清楚为什么将列表定义为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