简体   繁体   English

我不能将指针作为 STL 谓词的参数吗?

[英]Can't I get a pointer as a parameter of STL predicate?

How can I get a pointer?我怎样才能得到一个指针?

I want to put a pointer as a parameter to the lambda expression you see!我想把一个指针作为参数指向你看到的 lambda 表达式!

vector<unique_ptr<int>> arr{};

for (int i = 0; i < 100; ++i) {
  arr.emplace_back(i);
}

auto p = find_if(arr.begin(), arr.end(),
                 [](const unique_ptr<int>& a)  // error
                 { return *a == 10; });

cout << *p << endl;

The problem is that there is no implicit constructor for the class template std::unique_ptr that accepts an object of the template argument type.问题是 class 模板 std::unique_ptr 没有隐式构造函数,它接受模板参数类型的 object。

So this loop所以这个循环

for (int i = 0; i < 100; ++i)
{
    arr.emplace_back(i);
}

is incorrect.是不正确的。

Also this statement还有这个说法

cout << *p << endl;

is also incorrect.也是不正确的。 Instead write而是写

cout << **p << endl;

It seems you mean the following看来你的意思如下

for (int i = 0; i < 100; ++i)
{
    arr.emplace_back( make_unique<int>( i ) );
}

auto p = find_if(arr.begin(), arr.end(), [](const unique_ptr<int>& a) // error
{
    return *a == 10;
});

if ( p != arr.end() ) cout << **p << endl;

The problem is not the lambda, it is how you construct elements in your vector.问题不在于 lambda,而在于您如何在向量中构造元素。 This is how you want to do it:这就是你想要的方式:

for (int i = 0; i != 100; ++i) {
    arr.emplace_back( std::make_unique<int>( i ) );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 std::function 作为参数类型(需要函数指针版本)宁愿使用 STL 之类的模板,但它无法推导出参数 - Unable to use std::function as parameter type (need function pointer version) would rather template like the STL but then it can't deduce arguments 为什么我不能将函数指针作为模板参数传递给地图? - Why can't I pass a function pointer as a template parameter to a map? STL映射比较器能否以某种方式获取指向映射本身的指针? - Can the STL map comparator somehow get the pointer to the map itself? STL:指针关联排序容器:排序谓词模板 - STL: pointer associative sorted container: sorting predicate template 我可以在STL :: vector :: iterator上执行指针算术吗 - Can I do pointer arithmetic on an STL::vector::iterator 我可以创建一个接受函数和函子作为参数的谓词吗? - Can I create a predicate that will accept both functions and functors as a parameter? 无法将指针用作默认模板参数 - Can't use pointer as a default template parameter 如果我不需要完整而严格的订购,最有效的CUDA Thrust或C ++ STL排序谓词是什么? - What is the most efficient CUDA Thrust or C++ STL sort predicate to use if I don't need a full, strict ordering? 指针无法获取数据 - Pointer can't get data 无法使用C ++ STL映射获得正确答案 - Can't get the right answer with c++ STL map
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM