3

When I am using map.contains() in my C++ code using Visual Studio Code I get the following message:

class "std::map<int, int, std::less, std::allocator<std::pair<const int, int>>>" has no member "contains"

Thankfully, my code compiles when I run g++ -std=c++20 test.cc -o test, but VSCode keeps telling me there's a problem, which is quite irritating. This is my code:

#include <map>
using namespace std;

map<int, int> m;

bool contains_key(int idx) { return m.contains(idx); }

Has anyone had the same issue and knows how to fix it?

Wiktor
  • 71
  • 1
  • 9
  • 4
    [map::contains](https://en.cppreference.com/w/cpp/container/map/contains) was only added in C++20, so it won't compile unless you configure vscode to use that language revision. – cigien Oct 05 '21 at 19:29
  • 1
    look in `cpp_properties.json` – rioV8 Oct 05 '21 at 19:32
  • 1
    [this question](https://stackoverflow.com/questions/49397233/how-to-enable-c17-support-in-vscode-c-extension) on enabling C++17 support should also guide you to enabling C++20. – Drew Dormann Oct 05 '21 at 20:00

1 Answers1

3

std::map::contains() was introduced in C++20, which is why it works when you configure your compile to use C++20.

For earlier C++ versions, you will have to use std::map::find() or std::map::count() instead:

bool contains_key(int idx) { return m.find(idx) != m.end(); }
bool contains_key(int idx) { return m.count(idx) > 0; }
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770