For reference: C++17 std::optional error: expected primary-expression before 'auto'
My test code is below. My understanding is that my usage of auto
in this context is as outlined in the above reference for valid C++ code. However, I still get the error:
error: expected primary-expression before ‘auto’
if((auto pos = s2.find(c)) != -1)
What am I missing?
#include<string>
#include<set>
#include<algorithm>
#include<iostream>
using std::string;
using std::set;
using std::for_each;
using std::cout;
using std::endl;
void compare(const string& s1, const string& s2)
{
set<size_t>sequence;
for_each(s1.begin(),s1.end(),[&](const char& c){
if((auto pos = s2.find(c)) != -1)
{
sequence.insert(pos);
}
}
);
return;
}
int func()
{
string s1 = "some string";
string s2 = "some other string";
compare(s1,s2);
return 0;
}
int main() {
auto exit = (int (*)()) &func;
std::cout << exit() << std::endl;
}
The format for intializing a variable in an if statement and then using said variable in a condition is:
if(type name = initiallizer; condition)
So, for this case you need:
if(auto pos = s2.find(c); pos != -1)
Although you should use std::string::npos
instead of -1
to avoid magic numbers in your code.