c++ - 在 while 循环中连接值出错

标签 c++ string-concatenation boost-bind

我有一个 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/

相关文章:

c++ - 在 C++ 中将函数实现为宏的优点/缺点

c++ - 在单独的 C++ 线程中登录?

python - 将行连接到python中的字符串

c++ - 从结构数组中提取结构成员

c++ - boost::bind() 绑定(bind)额外的参数?

c++ - 缩放窗口时如何修复应用程序中的背景,sfml

c++ - 文件与文件流

java - Java 9 中的字符串连接是如何实现的?

c# - 仅当预检查为空字符串时连接 C# 字符串

c++ - boost::bind 的返回类型是什么?