Arnob Arnob - 3 months ago 10
C++ Question

Getting error although that should not be the case

I have the following codeblock:(note I'm a beginner in C++)

#include <iostream>
#include <string>
#include <map>


//using namespace std;

int main() {

std::map <std::string, std::string> mapping;

mapping ["This"] = "This";
mapping ["This"] = "This";
mapping ["This"] = "This";
mapping ["Thus"] = "This";
mapping ["Thus"] = "Das";
mapping ["Thus"] = "Bus";
mapping ["Mus"] = "Hus";


auto store = mapping.find("Thus");

std::cout << store << std::endl ;



return 0;




}


Although I have
iostream
included and map declared, why am I getting that map is not declared in the scope/ suggestion for
std::map
/suggestion for
iostream
?

Error

maptest.cc: In function ‘int main()’:
maptest.cc:7:1: error: ‘map’ was not declared in this scope
map <string,string>
^
maptest.cc:7:1: note: suggested alternative:
In file included from /usr/include/c++/4.8/map:61:0,
from maptest.cc:3:
/usr/include/c++/4.8/bits/stl_map.h:96:11: note: ‘std::map’
class map
^
maptest.cc:7:6: error: ‘string’ was not declared in this scope
map <string,string>
^
maptest.cc:7:6: note: suggested alternative:
In file included from /usr/include/c++/4.8/iosfwd:39:0,
from /usr/include/c++/4.8/ios:38,
from /usr/include/c++/4.8/ostream:38,
from /usr/include/c++/4.8/iostream:39,
from maptest.cc:1:
/usr/include/c++/4.8/bits/stringfwd.h:62:33: note: ‘std::string’
typedef basic_string<char> string;
^
maptest.cc:13:1: error: expected primary-expression before ‘}’ token
}
^

Answer

The error you're getting is because you're storing the result from find (which is not a std::string but an iterator) into a std::string.

auto ret = mapping.find("Thus");

if (ret != mapping.end())
    std::cout << ret->first << ": " << ret->second << std::endl;
Comments