3

我有这个有趣的情况。

我有一堆包含字符串的结构。

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

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

queue<string&> mStringQueue;

最后,我有一个接受 const string& 的函数

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<_Ty>::push”:无法将参数 1 从“String”转换为“String &(&)”

我很难将注意力集中在字符串引用和诸如此类的东西上,所以任何帮助将不胜感激

4

2 回答 2

7

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

另一种方法是存储可复制的指针

于 2012-05-04T20:17:57.130 回答
3

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

#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);
}
于 2012-05-07T01:57:52.437 回答