开发者

concatenate values in a while loop gone wrong

I have a boost::variant, which contains various types and I have a string which needs to look like this: type=D,S. The values in the variant are D and S respectively, the key is 'type'. It is a map<std::string, std::vector<variant> > where I'm now iterating the vector<variant> part

Now I first apply a static_visitor to my variant to do the appropriate conversion, which in this case might not be needed but for other type it would need conversion to a string.

Then I call this function called ConcatValue开发者_C百科s, part of a helper class. This class has a vector<string> v_accumulator defined, to hold temp results, as this function might be called several times in the while loop and I want to end up with a comma seperated value's list.

The problem is however that my vector v_accumulator is always empty on each function call? How does that make any sense, seeing as it is a class variable.

while(variant_values_iterator != values.end())
{
          variant var = *variant_values_iterator;
        boost::apply_visitor( add_node_value_visitor( boost::bind(&SerializerHelper::ConcatValues, helper, _1, _2), key, result), var);
        variant_values_iterator++;
}



std::string SerializerHelper::ConcatValues(std::string str, std::string key)
{
    v_accumulator.push_back(str); //the previous value is not in this vector???
    std::stringstream ss;
    std::vector<std::string>::iterator it = v_accumulator.begin();

    ss << key;
    ss << "=";

    for(;it != v_accumulator.end(); it++)
    {
        ss << *it;
        if (*it == v_accumulator.back())
            break;
        ss << ",";
    }

    return ss.str();

}


class SerializerHelper
{
public:
    std::string ConcatValues(std::string str, std::string key);

private:
    std::vector<std::string> v_accumulator;
};

maybe there is an easier way to concatenate the values of D,S in the value part of my original key/value pair?


The problem might be that, although v_accumulator is a class member, boost::bind copies its arguments by default. This means that ConcatValues is called on a copy of the helper, with its very own v_accumulator vector.

If you want a reference, you must use boost::ref :

boost::apply_visitor(add_node_value_visitor(
    boost::bind(&SerializerHelper::ConcatValues, boost::ref(helper), _1, _2), key, result), var);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜