queue <string&> errors </string&>

时间:2012-05-04 20:14:47

标签: c++ string data-structures reference queue

我有这种有趣的情况。

我有一堆带有字符串的结构。

struct foo
{
    string mStringName;
}
vector<foo> mFoos;

我还有一个字符串引用队列

queue<string&> mStringQueue;

最后,我有一个接受const字符串&amp;

的函数
void Bar(const string&);

见下这种情况。

//...in some loop
currentFoo = mFoos[index];

// Queue up the string name.
mStringQueue.push(currentFoo.mStringName);


//...Later on, go through our queue and pass each one to the function.

for (int queueIndex = 0; queueIndex < mStringQueue.size(); queueIndex++)
{
    Bar(mStringQueue.front());
    mStringQueue.pop();
}

这给了我以下编译错误:

错误C2664:'std :: queue&lt; _Ty&gt; :: push':无法将参数1从'String'转换为'String&amp;(&amp;)'

我是definitley在将字符串引用和诸如此类的东西包裹起来时遇到了麻烦,所以任何帮助都会非常感激

2 个答案:

答案 0 :(得分:6)

引用类型不符合可在标准容器中使用的类型的要求。特别是它们不可复制。请注意,虽然引用的对象可以是可复制的,但引用本身永远不可复制。

另一种方法是存储指针,它们是可复制的。

答案 1 :(得分:1)

标准容器要求“T是可复制的(严格来说,CopyConstructible)”或“T是可移动的(严格来说,MoveConstructible)”。 如果需要reference元素,可以使用std :: queue&lt;的std ::的reference_wrapper&LT; T> &GT;

#include <cassert>
#include <queue>
#include <functional> // std::reference_wrapper, std::ref

int main()
{
    int a = 1;
    int b = 2;
    int c = 3;

    std::queue<std::reference_wrapper<int>> que;

    que.push(std::ref(a));
    que.push(std::ref(b));
    que.push(std::ref(c));

    while (!que.empty()) {
        que.front() += 1;
        que.pop();
    }

    assert(a == 2);
    assert(b == 3);
    assert(c == 4);
}