我正在使用自定义类型 vector 的线程安全队列。它显示以下错误。我不确定我在这里遗漏了什么。
Error C2664 'std::vector>::vector(std::vector<_Ty,std::allocator<_Ty>> &&,const _Alloc &) noexcept()': cannot convert argument 2 from 'int' to 'const std::allocator<_Ty> &'<A>.
#include <mutex>
#include <condition_variable>
#include <queue>
#include <memory>
#include <iostream>
#include <thread>
template<typename T>
class threadsafe_queue
{
private:
mutable std::mutex mut;
std::queue<T> data_queue;
std::condition_variable data_cond;
public:
threadsafe_queue()
{}
threadsafe_queue(threadsafe_queue const& other)
{
std::lock_guard<std::mutex> lk(other.mut);
data_queue = other.data_queue;
}
void push(T new_value)
{
std::lock_guard<std::mutex> lk(mut);
data_queue.push(new_value);
data_cond.notify_one();
}
void wait_and_pop(T& value)
{
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this] {return !data_queue.empty(); });
value = data_queue.front();
data_queue.pop();
}
std::shared_ptr<T> wait_and_pop()
{
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this] {return !data_queue.empty(); });
std::shared_ptr<T> res(std::make_shared<T>(data_queue.front()));
data_queue.pop();
return res;
}
bool try_pop(T& value)
{
std::lock_guard<std::mutex> lk(mut);
if (data_queue.empty)
return false;
value = data_queue.front();
data_queue.pop();
}
std::shared_ptr<T> try_pop()
{
std::lock_guard<std::mutex> lk(mut);
if (data_queue.empty())
return std::shared_ptr<T>();
std::shared_ptr<T> res(std::make_shared<T>(data_queue.front()));
data_queue.pop();
return res;
}
bool empty() const
{
std::lock_guard<std::mutex> lk(mut);
return data_queue.empty();
}
};
class cp_data
{
public:
int num;
double time;
cp_data(int a, double b)
{
num = a;
time = b;
}
};
int main() {
std::vector<cp_data> data(1,2);
threadsafe_queue<std::vector<cp_data>> temp_queue;
temp_queue.push(data);
system("pause");
}
最佳答案
vector 没有构造函数将其参数转发到它为创建单个元素而持有的数据类型。
但是,您可以使用 std::initializer_list
构造函数传递一个对象(如果您愿意,也可以传递多个对象):
改变
std::vector<cp_data> data(1,2);
到
std::vector<cp_data> data{{1,2}};
或者,您可以在语法上更明确地创建 cp_data
对象:
std::vector<cp_data> data{cp_data(1,2)};
{1,2}
创建 cp_data
对象,然后该对象通过创建的 std::initializater_list
传递给 vector 的构造函数通过外部 {...}
的
直播:https://godbolt.org/g/s2AwJU
作为旁注,vector::emplace_back
的工作方式与您的代码尝试构建对象的方式相同 - 它将您的参数转发给 cp_data
的构造函数为了创建一个对象存储在 vector 中。
关于C++:自定义数据类型 vector 错误队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51795998/