jeudi 7 septembre 2023

C++: Declare iterator in if statement

There doesn't seem to be any problem with my code, I even asked gpt4 and it also said there is no problem, but when I compile it emits an error with the if statement, is this because I declared the iterator? The program is here:


#include <functional>
#include <iostream>
#include <map>
#include <string>
using namespace std;

std::map<std::string, std::function<void(const std::string&, int&)>>
    invoke_decision;

void exampleFunction(const std::string& msg, int& num) {
  cout << "Message: " << msg << ", Number: " << num << endl;
}

int main(int argc, char** argv) {
  invoke_decision["a"] = exampleFunction;

  string target_url = "a";
  int exampleNum = 42;

  if ((auto iter = invoke_decision.find(target_url)) != invoke_decision.end()) {
    iter->second(target_url, exampleNum);
  }

  return 0;
}


then compile it, here is the errors:

++ -std=c++20 -o test test.cc
test.cc: In function ‘int main(int, char**)’:
test.cc:20:8: error: expected primary-expression before ‘auto’
   20 |   if ((auto iter = invoke_decision.find(target_url)) != invoke_decision.end()) {
      |        ^~~~
test.cc:20:8: error: expected ‘)’ before ‘auto’
   20 |   if ((auto iter = invoke_decision.find(target_url)) != invoke_decision.end()) {
      |       ~^~~~
      |        )
test.cc:22:4: error: expected ‘)’ before ‘return’
   22 |   }
      |    ^
      |    )
   23 | 
   24 |   return 0;
      |   ~~~~~~
test.cc:20:6: note: to match this ‘(’
   20 |   if ((auto iter = invoke_decision.find(target_url)) != invoke_decision.end()) {
      |      ^

Aucun commentaire:

Enregistrer un commentaire