I need to store a string along with an integer in a circular buffer and then have to iterate through it, searching (with a substr) for existence of a string which then gets copied along with the integer into result buffer. I've written the below proof of concept code but it terminates pre-maturely after the first time &res
gets copied into out
and I'm not exactly sure why, can anyone help me here?
This is what I have so far:
#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;
}
Where the output is:
./circular
buff.size() 0
result[0] ABC 78
ABC does not contain ABCDE
buff.size() 2
Command terminated
I'm not sure why g++
needs me to do memcpy(&res,&itr,sizeof(cb_dat_t));
, itr
is a pointer already, isn't it? It complains when I do memcpy(&res,itr,sizeof(cb_dat_t));
instead.
You shouldn't be using memcpy
at all. Since cb_dat_t
is not a POD type (in this case because it contains a member with a constructor), you should be using the assignment operation to copy cb_dat_t
objects. The four memcpy
calls in buffer_check
can be replaced with
*out = in;
res = *itr;
res = in;
*out = res;
memcpy
will not handle std::string
properly. The compiler generated default assignment operator for cb_dat_t
will properly copy all members of the structure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.