I am trying to solve a simple Fibonacci problem using the lambda function, but I came across this error and I cant solve it.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string str;
auto N{0};
auto i{0};
cout<<"Digite o valor de N desejado: ";
getline(cin,str); //pega linha
stringstream(str) >> N;
if (N == 0){cout<<0;}
else if (N == 1){cout<<1;}
else
{
vector<int> v{0,1}; //cria vetor v
for_each(v.begin(),N,
[&](){
v.push_back(v[i]+v[i+1]);
i++;
});
i = 0;
for_each(v.begin(),N,
[&](){
cout<<v[i];
i++;
});
}
return 0;
}
And the error is the following:
quest1.cpp: In function ‘int main()’: quest1.cpp:30:4: error: no matching function for call to ‘for_each(std::vector<int>::iterator, int&, main()::<lambda()>)’ });
^ In file included from /usr/include/c++/6.3.1/algorithm:62:0,
from quest1.cpp:5: /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note: candidate: template<class _IIter, class _Funct> _Funct std::for_each(_IIter,
_IIter, _Funct)
for_each(_InputIterator __first, _InputIterator __last, _Function __f)
^~~~~~~~ /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note: template argument deduction/substitution failed: quest1.cpp:30:4: note: deduced conflicting types for parameter ‘_IIter’ (‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’ and ‘int’) });
^ quest1.cpp:38:5: error: no matching function for call to ‘for_each(std::vector<int>::iterator, int&, main()::<lambda()>)’
});
^ In file included from /usr/include/c++/6.3.1/algorithm:62:0,
from quest1.cpp:5: /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note: candidate: template<class _IIter, class _Funct> _Funct std::for_each(_IIter,
_IIter, _Funct)
for_each(_InputIterator __first, _InputIterator __last, _Function __f)
^~~~~~~~ /usr/include/c++/6.3.1/bits/stl_algo.h:3763:5: note: template argument deduction/substitution failed: quest1.cpp:38:5: note: deduced conflicting types for parameter ‘_IIter’ (‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’ and ‘int’)
});
There's two problems in your code. One (already covered by other answers), you're passing the number of iterations as the second parameter to std::for_each, but it actually expects an end iterator. std::for_each(a, b, f) is designed to iterate from iterator a to iterator b and call f on each element in that range.
The second problem is more fundamental: if you modify the vector while iterating over it, you'll get Undefined Behaviour because any modification operation invalidates all iterators to the vector.
Looking at your code, it seems you want the first loop to a normal counting loop and not iteration over the container. The second loop could be done with for_each and a lambda:
vector<int> v{0,1};
for (int i = 0; i < N; ++i) {
v.push_back(v[i] + v[i+1]);
}
for_each(v.begin(), v.end(),
[](int element) {
cout << element;
}
);
Notice that the functor used in for_each is not nullary: the algorithm will pass the element to it.
Alternatively, the printing functionality could be implemented without lambdas:
copy(v.begin(), v.end(), ostream_iterator<int>(cout));
Or, if you prefer to keep the loop, you could just as well use a range-based for loop instead of for_each. The code will be shorter and [subjective]easier to read[/subjective]:
for (int elem : v) {
std::cout << elem;
}
std::for_each requires (as the error tries to tell you) an iterator where to start looping and an iterator where to end. You however are passing an iterator and an int, which are "conflicting types". If you want to loop over an whole vector do something like that:
std::vector<int> v{1, 2, 3};
std::for_each(v.begin(), // start at the front
v.end(), // loop over each element
[&] (int& i) {
i++;
});
If you just need to loop over a part of the vector do that
std::vector<int> v{1, 2, 3};
std::for_each(v.begin(), // start at the front
v.begin() + 2, // loop over the first two elements
[&] (int& i) {
i++;
});
You are not using the for_each function correctly. C++ does not know the signature you are using. Please refer to the documentation, e.g. for_each.
The compiler says exactly that. The second parameter of the for_each you are calling is of type int&, but the signature is for_each(InputIterator, InputIterator, Function) and not for_each(InputIterator, int&, Function), so it fails to compile.
Related
I saw this example of how to do it in C++11:
std::unique(v.begin(), v.end(), [](float l, float r)
{
return std::abs(l - r) < 0.01;
});
However, this fails for me in C++03:
error: template argument for 'template<class _FIter, class _BinaryPredicate> _FIter std::unique(_FIter, _FIter, _BinaryPredicate)' uses local type 'CRayTracer::myFunc()::<lambda(float, float)>'
How can I do this in C++03? I think Lambdas may have already existed, and functors/function objects existed, right? Just looking for a simple solution, does not need to be extendable - it will only ever be used here.
Here is an example of code which will not compile for me:
#include <iostream>
#include <vector>
#include <algorithm>
int main(){
std::vector<float> v;
v.push_back(1.0);
v.push_back(1.0);
v.push_back(3.5);
v.push_back(3.5);
struct approx_equal
{
bool operator()(float l, float r)
{
return std::abs(l - r) < 0.01;
}
};
approx_equal f;
std::unique(v.begin(), v.end(),f);
}
Here's the error it produced:
testUnique.cpp: In function 'int main()':
testUnique.cpp:21:37: error: no matching function for call to 'unique(std::vector<float>::iterator, std::vector<float>::iterator, main()::approx_equal&)'
21 | std::unique(v.begin(), v.end(),f);
| ^
In file included from C:/msys64/mingw64/include/c++/9.2.0/algorithm:62,
from testUnique.cpp:3:
C:/msys64/mingw64/include/c++/9.2.0/bits/stl_algo.h:995:5: note: candidate: 'template<class _FIter> _FIter std::unique(_FIter, _FIter)'
995 | unique(_ForwardIterator __first, _ForwardIterator __last)
| ^~~~~~
C:/msys64/mingw64/include/c++/9.2.0/bits/stl_algo.h:995:5: note: template argument deduction/substitution failed:
testUnique.cpp:21:37: note: candidate expects 2 arguments, 3 provided
21 | std::unique(v.begin(), v.end(),f);
| ^
In file included from C:/msys64/mingw64/include/c++/9.2.0/algorithm:62,
from testUnique.cpp:3:
C:/msys64/mingw64/include/c++/9.2.0/bits/stl_algo.h:1025:5: note: candidate: 'template<class _FIter, class _BinaryPredicate> _FIter std::unique(_FIter, _FIter, _BinaryPredicate)'
1025 | unique(_ForwardIterator __first, _ForwardIterator __last,
| ^~~~~~
C:/msys64/mingw64/include/c++/9.2.0/bits/stl_algo.h:1025:5: note: template argument deduction/substitution failed:
testUnique.cpp: In substitution of 'template<class _FIter, class _BinaryPredicate> _FIter std::unique(_FIter, _FIter, _BinaryPredicate) [with _FIter = __gnu_cxx::__normal_iterator<float*, std::vector<float> >; _BinaryPredicate = main()::approx_equal]':
testUnique.cpp:21:37: required from here
testUnique.cpp:21:37: error: template argument for 'template<class _FIter, class _BinaryPredicate> _FIter std::unique(_FIter, _FIter, _BinaryPredicate)' uses local type 'main()::approx_equal'
21 | std::unique(v.begin(), v.end(),f);
| ^
testUnique.cpp:21:37: error: trying to instantiate 'template<class _FIter, class _BinaryPredicate> _FIter std::unique(_FIter, _FIter, _BinaryPredicate)'
And here was my set of flags:
g++ -c -g -O3 -Wp,-D_FORTIFY_SOURCE=2 -m64 -Wshadow -Wall -DMX_COMPAT_32 -fexceptions -fno-omit-frame-pointer -D__WIN32__ -std=c++03 testUnique.cpp -o testUnique.o
I think Lambdas may have already existed,
No. Lambdas have been introduced in C++11.
... and functors/function objects existed, right?
Functors are simply objects with an operator(), so they always have been there (though not sure when the term "functor" was actually introduced for them).
For the formal correct way to put it I refer you to other references, sloppy speaking this
auto f = [](float l, float r){
return std::abs(l - r) < 0.01;
};
f(0.1,0.2);
Is equivalent to
struct unnamed {
bool operator()(float l, float r) {
return std::abs(l - r) < 0.01;
}
};
unnamed f;
f(0.1,0.2);
I.e. you can always replace a lambda with a handwritten functor class. Create an instance of the functor and pass that instead of the lambda.
Complete example:
#include <iostream>
#include <vector>
#include <algorithm>
struct approx_equal{
bool operator()(float l, float r) {
return std::abs(l - r) < 0.01;
}
};
int main(){
std::vector<float> v{1.0, 1.0, 3.5, 3.5 };
approx_equal f;
v.erase(std::unique(v.begin(), v.end(),f),v.end());
// sorry this is c++11, replace with iterator loop to see output pre-c++11
for (const auto& x : v) std::cout << x << " ";
}
PS: In C++03 you cannot define the functor class locally and then use it as template parameter (note you do not explicitly pass it as template parameter, but unique has to deduce its type from the parameter you pass in).
Lambdas don't exist in C++03, they were introduced in C++11.
Since your lambda example does not need to capture values, you can replace it with a simple standalone function, you don't need a functor, eg:
#include <iostream>
#include <vector>
#include <algorithm>
bool approx_equal(float l, float r) {
return std::abs(l - r) < 0.01;
}
int main(){
std::vector<float> v;
v.push_back(1.0);
v.push_back(1.0);
v.push_back(3.5);
v.push_back(3.5);
std::unique(v.begin(), v.end(), approx_equal);
}
However, you can use a functor, too. In your attempt to use a functor, you simply defined the functor type inside of main() itself, making it a local type, which the compiler complained about. Define the functor type in global scope instead (you can still use a local variable to instantiate the type), eg:
#include <iostream>
#include <vector>
#include <algorithm>
struct approx_equal {
bool operator()(float l, float r) {
return std::abs(l - r) < 0.01;
}
};
int main(){
std::vector<float> v;
v.push_back(1.0);
v.push_back(1.0);
v.push_back(3.5);
v.push_back(3.5);
approx_equal f;
std::unique(v.begin(), v.end(), f);
// or:
// std::unique(v.begin(), v.end(), approx_equal{});
}
I am trying to insert the values present in a vector into a unordered_map. I passed the vector to another function and declare an unordered_map and an iterator to the vector. But while compiling it gives error(below). I would like to understand why does this fail. Searching online has given me a rough idea as to what might be wrong but it is not clear to me:
1. When i pass the vector without '&', a copy of the vector is sent to the function. What does this exactly mean? How does this works internally?
2. What kind of values does make_pair take? Shouldn't 'n' and '*it' just be simple numerical values that make_pair should accept?
#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;
void readValues(vector<int>&v, int n)
{
int temp;
while(n--)
{
cin>>temp;
v.push_back(temp);
}
}
unordered_map<int, int> storeinhashmap(vector<int>v, int n)
{
vector<int>::iterator it=v.begin();
unordered_map<int,int>h;
int temp;
while(n--)
{
temp = *it;
//cout<<"iter "<<*it<<" "<<++n<<endl;
h.insert(make_pair<int,int>(n, *it));
it++;
}
return h;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n, x;
cin>>n;
vector<int>v;
readValues(v, n);
cin>>x;
unordered_map<int, int>h = storeinhashmap(v, n);
//char ans = checksumisx(h, n);
}
return 0;
}
Error -
harshit#harshit-5570:~/Desktop/geeksforgeeks$ g++ -std=c++14 key_pair.cpp
key_pair.cpp: In function ‘std::unordered_map<int, int> storeinhashmap(std::vector<int>, int)’:
key_pair.cpp:26:43: error: no matching function for call to ‘make_pair(int&, int&)’
h.insert(make_pair<int,int>(n, *it));
^
In file included from /usr/include/c++/5/bits/stl_algobase.h:64:0,
from /usr/include/c++/5/bits/char_traits.h:39,
from /usr/include/c++/5/ios:40,
from /usr/include/c++/5/ostream:38,
from /usr/include/c++/5/iostream:39,
from key_pair.cpp:1:
/usr/include/c++/5/bits/stl_pair.h:276:5: note: candidate: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
make_pair(_T1&& __x, _T2&& __y)
^
/usr/include/c++/5/bits/stl_pair.h:276:5: note: template argument deduction/substitution failed:
key_pair.cpp:26:43: note: cannot convert ‘n’ (type ‘int’) to type ‘int&&’
h.insert(make_pair<int,int>(n, *it));
What kind of values does make_pair take? Shouldn't 'n' and '*it' just be simple numerical values that make_pair should accept?
std::make_pair is declared as follows (e.g. 20.3.3 in n3337):
template <class T1, class T2>
pair<V1, V2> make_pair(T1&& x, T2&& y);
Thus if we explicitly set these template parameters like you, no type deductions occur and this function yields
pair<int, int> make_pair(int&& x, int&& y);
Then
h.insert(make_pair<int,int>(n, *it));
shows compilation error because both n and *it are lvalues, not int&&.
This error is easily removed if we rewrite this line as follows:
h.insert(make_pair<int,int>(std::move(n), std::move(*it)));
But the most simple way to avoid this error is removing explicit template parameters like this:
h.insert(make_pair(n, *it));
As you do not want to modify the vector, you can pass it as const reference argument in order to avoid useless copies:
unordered_map<int, int> storeinhashmap(const vector<int>& v, int n)
{
// Check that the number of elements to be inserted
// is less than the size of vector
if (n < 0 || n > v.size()) {
throw invalid_argument("Wrong number of vector elements to be inserted.");
}
unordered_map<int,int>h;
for (size_t i = 0; i < (size_t)n; i++) {
h.insert(make_pair(n-i, v[i]));
}
return h;
}
In addition, I understood that n is the number of elements of the vector<int> to be inserted within unordered_map<int, int>, hence I have included a previous size check.
This question already has answers here:
Why isn't vector<bool> a STL container?
(6 answers)
Closed 4 years ago.
I have the following code snippet, which takes the std::vector<int> list and writes a zero in all vector elements. This example is working perfectly fine.
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<int> list {1, 1, 2};
auto reset = [](int & element){element = 0;};
auto print = [](int element) {std::cout << element << " ";};
std::for_each(list.begin(), list.end(), reset);
std::for_each(list.begin(), list.end(), print);
}
If I take change the type of the vector from int to bool, the code will not compile.
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<bool> list {true, true, false};
auto reset = [](bool & element){element = false;};
auto print = [](int element) {std::cout << element << " ";};
std::for_each(list.begin(), list.end(), reset);
std::for_each(list.begin(), list.end(), print);
}
https://godbolt.org/g/2EntgX
I don't understand the compiler error message:
/opt/compiler-explorer/gcc-7.2.0/lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/stl_algo.h:3884:2: error: no matching function for call to object of type '(lambda at
:7:18)'
__f(*__first);
^~~
:10:10: note: in instantiation of function template
specialization 'std::for_each:7:18)>' requested here
std::for_each(list.begin(), list.end(),reset);
^
:7:18: note: candidate function not viable: no known
conversion from 'std::_Bit_iterator::reference' (aka
'std::_Bit_reference') to 'bool &' for 1st argument
auto reset = [](bool & element){element = false;};
^
:7:18: note: conversion candidate of type 'void (*)(bool &)'
Why does std::foreach work with a std::vector<int>, but does not work with a std::vector<bool>?
Is the memory optimisation of an std::vector<bool> (see here ) part of the answer?
Reason
The problem stems from the fact that dereferencing an iterator that came from std::vector<bool> doesn't return bool&, but rather a proxy object. Thus, it is not regarded as stl container (thanks to #KillzoneKid).
Fix
Use auto element in the parameter list. In general, if you don't care about the type, use auto&& in the lambda parameter list.
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<bool> list {true, true, false};
auto reset = [](auto && element){element = false;};
auto print = [](int element) {std::cout<< element << " ";};
std::for_each(list.begin(), list.end(),reset);
std::for_each(list.begin(), list.end(),print);
}
Demo.
Trying to use auto& will trigger compilation error again, as the proxy returned is not lvalue, but rvalue. Thus, auto&& has even more benefits than usual.
I'm trying to find bounds in the part of vector from next iterator position to the end of the vector.
The code is:
#include <algorithm>
#include <vector>
#include <iostream>
int
main()
{
typedef std::vector<int> Vector;
Vector v;
v.push_back(3);
v.push_back(7);
v.push_back(15);
v.push_back(21);
std::sort(v.begin(), v.end());
for (Vector::const_iterator i = v.begin(); i != v.end(); ++i) {
Vector::const_iterator low = std::lower_bound(i+1, v.end(), -10-*i);
Vector::const_iterator high = std::upper_bound(i+1, v.end(), 10-*i);
for (Vector::const_iterator j = low; j != high; ++j) {
std::cout << *i << "~" << *j << std::endl;
}
}
return 0;
}
Unfortunately, std::lower_bound(i+1, v.end(), -10-*i) triggers compilation error which I cannot understand:
c++ -O3 -ggdb -std=c++11 -W -Wall -pedantic -Wl,-stack_size -Wl,0x1000000 2sum.cc -o 2sum
2sum.cc:26:26: error: no matching function for call to 'lower_bound'
V::const_iterator lo = std::lower_bound(i+1, a.end(), -1...
^~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:4085:1: note:
candidate template ignored: deduced conflicting types for parameter
'_ForwardIterator' ('__wrap_iter<const long *>' vs.
'__wrap_iter<long *>')
lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp...
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:4070:1: note:
candidate function template not viable: requires 4 arguments, but 3 were
provided
lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp...
^
What is the problem with the statement above and how to properly call std::lower_bound with i+1 iterator?
The error probably says that it can't deduce the template argument - i is const_iterator while v.end() returns iterator. This should do the trick:
std::lower_bound( i+1, v.cend(), -10-*i);
^^^^^^^^
On OS X Mavericks, using boost 1.55.0 and clang-500.2.79 (based on LLVM 3.3svn), I'm trying to iterate over a sub-range in a std::map using boost::for_each and boost:sub_range. In my function-object, I expect to receive a std::pair &. Instead, I seem to receive a const std::pair &. Why?
#include <map>
#include <boost/range/algorithm.hpp>
#include <boost/range/sub_range.hpp>
using std::map;
using std::begin;
using std::end;
using std::pair;
using boost::for_each;
using boost::sub_range;
int main()
{
map<int, int> myMap;
sub_range<decltype(myMap)> s{
begin(myMap),
end(myMap)
};
auto f1 = [&](const pair<int, int> &) {
};
for_each(s, f1); // Compiles fine
auto f2 = [&](pair<int, int> &) {
};
for_each(s, f2); // Fails to compile
}
/Users/ambarish> clang++ main.cxx
In file included from main.cxx:1:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:371:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:18:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/algorithm:793:9: error: no matching function for call to object of type '<lambda at main.cxx:24:15>'
__f(*__first);
^~~
/usr/local/include/boost/range/algorithm/for_each.hpp:80:12: note: in instantiation of function template specialization
'std::__1::for_each<std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::pair<int, int>, std::__1::__tree_node<std::__1::pair<int, int>, void *> *, long> >, <lambda at main.cxx:24:15> >'
requested here
return std::for_each<
^
main.cxx:26:5: note: (skipping 1 context in backtrace; use -ftemplate-backtrace-limit=0 to see all)
for_each(s, f2);
^
main.cxx:24:15: note: candidate function not viable: no known conversion from 'value_type' (aka 'pair<__key_type, __mapped_type>') to 'pair<int, int> &' for 1st argument
auto f2 = [&](pair<int, int> &) {
^
1 error generated.
It doesn't compile because the value type of std::map<int, int> is not std::pair<int,int> but std::pair<const int, int>.
The reason first one (f1) compiles is because std::pair has got this constructor:
template< class U1, class U2 >
pair( pair<U1, U2>&& p );
and because f1 takes the argument by const reference. Now there's a suitable conversion which produces a temporary that can bind to a const reference easily.
Fix:
auto f2 = [&](pair<const int, int> &) { };
// or
auto f2 = [&](pair<int, int>) { };
The code appears to be using std::for_each in the boost library implementation, and C++11 style standard lambdas are being passed to the for_each function at any rate. It really depends on how the library passes the container's iterators to the std::for_each