我有一个 boost::variant
,其中包含各种类型,我有一个字符串需要如下所示:type=D,S。 variant 中的值分别是 D 和 S,key 是'type'。这是一个map<std::string, std::vector<variant> >
我现在在哪里迭代 vector<variant>
部分
现在我首先将 static_visitor 应用于我的变体以进行适当的转换,在这种情况下可能不需要,但对于其他类型,它需要转换为字符串。
然后我将这个函数称为 ConcatValues
,辅助类的一部分。这个类有一个 vector<string> v_accumulator
已定义,用于保存临时结果,因为此函数可能会在 while 循环中多次调用,我希望以逗号分隔值列表结束。
问题是我的 vector v_accumulator
每次函数调用总是空的?这有什么意义,因为它是一个类变量。
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;
};
也许有一种更简单的方法可以将 D、S 的值连接到我的原始键/值对的值部分?
最佳答案
问题可能是,尽管v_accumulator
是一个类成员,但boost::bind
默认复制它的参数。这意味着 ConcatValues
是在 helper
的拷贝上调用的,它有自己的 v_accumulator
vector 。
如果你想要引用,你必须使用boost::ref
:
boost::apply_visitor(add_node_value_visitor(
boost::bind(&SerializerHelper::ConcatValues, boost::ref(helper), _1, _2), key, result), var);
关于c++ - 在 while 循环中连接值出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4448570/