1

Hi I have a code which has structure explained below. This is not the actual code but I've tried to simulate the problem and it gives same error.

I've a file called classTest.cpp which contains:

#include<iostream>
#include "header.h"

using namespace std;
int main()
{
    test f;
    f.insert(10);
    cout<<f.search(10)<<endl;
    return 0;
}

header.h contains following code:

#include<unordered_set>
class test
{
    public:
    int apple;
    unordered_set<int> set;
    bool search(int a);
    void insert(int a);
};
bool test::search(int a)
{
    if(apple!=a)
        return false;
    return true;
        /*
    if(set.find(a) == set.end())
        return false;
    return true;*/
}


void test::insert(int a)
{
    apple = a;
    //set.insert(a);
}

When i compile classTest.cpp I get following error:

header.h:6:2: error: ‘unordered_set’ does not name a type
  unordered_set<int> set;

But when I copy the header.h content and paste it into classTest.cpp it works fine. I am unable to understand the reason. Is there some basic concept that I'm missing?

mribot
  • 519
  • 1
  • 11
  • 29
  • 2
    You're including it *before* the `using namespace std;`, but (apparently) when you pasted it in, you put it after that. Change it to `std::unordered_set` in the header, and see if things don't work a bit better. – Jerry Coffin Oct 21 '15 at 00:38
  • 2
    Use `std::unordered_set` instead. An since you seem to not know what `using namespace std;` does: Just stop using it and qualify the names with `std::` instead. – Baum mit Augen Oct 21 '15 at 00:39
  • Oh! It was such stupid mistake. Working now. – mribot Oct 21 '15 at 00:43
  • That's not stupid. Sitting down with shuriken in your pocket... That's stupid. – user4581301 Oct 21 '15 at 00:50

1 Answers1

1

As stated in the comments: you are attempting to use unordered_set without qualifying the namespace it comes from. Your compiler thus doesn't know what type it is.

This works when you copy your declaration of test into classTest.cpp because that file has a using namespace std.

You should always qualify your types with their namespace (if for no other reason than to avoid problems like this). In this case, to solve your problem, you should write:

std::unordered_set<int> set;
Community
  • 1
  • 1
Tas
  • 7,023
  • 3
  • 36
  • 51
  • Thanks for the answer. It was a silly mistake. I assumed that there is no need for std:: as I specified namespace but missed the ordering. But yes it is solved now. I moved importing the header after using namespace std. – mribot Oct 21 '15 at 02:52