【问题标题】:storing structure data in circular buffer在循环缓冲区中存储结构数据
【发布时间】:2018-12-17 17:32:33
【问题描述】:

我需要将一个字符串和一个整数一起存储在一个循环缓冲区中,然后必须遍历它,搜索(使用 substr)是否存在一个字符串,然后将该字符串与整数一起复制到结果缓冲区中。 我已经编写了下面的概念验证代码,但它在 &res 第一次被复制到 out 后提前终止,我不确定为什么,有人可以在这里帮助我吗?
这是我目前所拥有的:

#include <iostream>
#include <boost/circular_buffer.hpp>
#include <boost/algorithm/string/predicate.hpp>

#define CB_SZ   4
#define ARR     7

struct cb_dat_t{
    std::string lp;
    int cnf;
};

int buffer_check(cb_dat_t &in, boost::circular_buffer<cb_dat_t> &buff, cb_dat_t *out);
 int main(void)
 {
    int i = 0;
    cb_dat_t in[ARR];
    cb_dat_t out;
    boost::circular_buffer<cb_dat_t> cb(CB_SZ);

    in[0].lp = "ABC";
    in[0].cnf = 78;
    in[1].lp = "ABCDE";
    in[1].cnf = 63;
    in[2].lp = "AB";
    in[2].cnf = 92;
    in[3].lp = "1234";
    in[3].cnf = 85;
    in[4].lp = "23";
    in[4].cnf = 71;
    in[5].lp = "ABC";
    in[5].cnf = 63;
    in[6].lp = "BC";
    in[6].cnf = 71;

    for (i=0; i<ARR; i++) {
    buffer_check(in[i], cb, &out);
    std::cout << "result[" << i << "] " << out.lp << " " << out.cnf << std::endl;
    }
    std::cout << "all done!" <<std::endl;
return 0;
 }

int buffer_check(cb_dat_t &in, boost::circular_buffer<cb_dat_t> &buff, cb_dat_t *out)
{
    cb_dat_t res;

    if (!buff.size()){
        std::cout << "buff.size() " << buff.size() << std::endl;
        buff.push_back(in);
        memcpy(out,&in,sizeof(cb_dat_t));
        return 0;
    }

    boost::circular_buffer<cb_dat_t>::iterator itr = buff.begin();
    while (itr!=buff.end()) {
        if (boost::contains(itr->lp,in.lp)) {
            std::cout << itr->lp << " contains " << in.lp << std::endl;
            memcpy(&res,&itr,sizeof(cb_dat_t));
        } else {
            std::cout << itr->lp << " does not contain " << in.lp <<std::endl;
            memcpy(&res,&in,sizeof(cb_dat_t));
        }
        itr++;
    }
    buff.push_back(in);
    memcpy(out,&res,sizeof(cb_dat_t));
    std::cout << "buff.size() " << buff.size() << std::endl;
    return 0;
}

输出在哪里:

./circular
buff.size() 0
result[0] ABC 78
ABC does not contain ABCDE
buff.size() 2

Command terminated

我不知道为什么g++ 需要我做memcpy(&amp;res,&amp;itr,sizeof(cb_dat_t));,itr 已经是一个指针,不是吗?当我改为 memcpy(&amp;res,itr,sizeof(cb_dat_t)); 时它会抱怨。

【问题讨论】:

    标签: c++ pointers boost reference iterator


    【解决方案1】:

    您根本不应该使用memcpy。由于 cb_dat_t 不是 POD 类型(在这种情况下,因为它包含一个带有构造函数的成员),因此您应该使用赋值操作来复制 cb_dat_t 对象。 buffer_check 中的四个memcpy 调用可以替换为

    *out = in;
    res = *itr;
    res = in;
    *out = res;
    

    memcpy 将无法正确处理 std::string。编译器为cb_dat_t 生成的默认赋值运算符将正确复制结构的所有成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多