2015-06-12 20 views
7

Sto imparando C++, quindi sto lavorando al libro Programmazione: principi e pratica usando C++.Come risolvere "<hash_map> è deprecato e sarà RIMOSSO. Utilizzare <unordered_map>"?

Sono al primo trapano, che è come fare un 'Ciao mondo!' programma utilizzando Microsoft Visual Studio 2015. Ho usato il codice sorgente come previsto nel libro.

#include "../../std_lib_facilities.h" //header file recommended by book 
int main()        //C++ programs start by executing the function main 
{ 
    cout <<"Hello, World!\n"; //output "Hello, World!" 
    keep_window_open();   //wait for a character to be entered 
    return 0; 
} 

Tuttavia, ricevo due errori quando si tenta di costruire un programma eseguibile, che sono i seguenti:

IntelliSense: static assertion failed with "<hash_map> is  
deprecated and will be REMOVED. Please use <unordered_map>. You can define 
_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS to acknowledge that you have 
received this warning." 
Project: Hello, World! 
c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\hash_map 
Line 14 

Error C2338 <hash_map> is deprecated and will be REMOVED. Please use 
<unordered_map>. You can define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS to 
acknowledge that you have received this warning.  
Project: Hello, World! 
c:\program files (x86)\microsoft visual studio 14.0\vc\include\hash_map 
Line 17 

Potrebbe spiegarmi come posso rimediare a questo?

Il codice nel std_lib_facilities.h è la seguente:

/* 
    simple "Programming: Principles and Practice using C++" course header to 
    be used for the first few weeks. 
    It provides the most common standard headers (in the global namespace) 
    and minimal exception/error support. 

    Students: please don't try to understand the details of headers just yet. 
    All will be explained. This header is primarily used so that you don't  have 
    to understand every concept all at once. 

    Revised April 25, 2010: simple_error() added 
*/ 

#ifndef H112 
#define H112 201004L 

#include<iostream> 
#include<fstream> 
#include<sstream> 
#include<cmath> 
#include<cstdlib> 
#include<string> 
#include<list> 
#include<vector> 
#include<algorithm> 
#include<stdexcept> 

//--------------------------------------------------------------------------- --- 

#ifdef _MSC_VER 
#include <hash_map> 
using stdext::hash_map; 
#else 
#include <ext/hash_map> 
using __gnu_cxx::hash_map; 

namespace __gnu_cxx { 

    template<> struct hash<std::string> 
    { 
     size_t operator()(const std::string& s) const 
     { 
      return hash<char*>()(s.c_str()); 
     } 
    }; 

} // of namespace __gnu_cxx 
#endif 

//--------------------------------------------------------------------------- --- 

#define unordered_map hash_map 

//--------------------------------------------------------------------------- --- 

typedef long Unicode; 

//--------------------------------------------------------------------------- --- 

using namespace std; 

template<class T> string to_string(const T& t) 
{ 
    ostringstream os; 
    os << t; 
    return os.str(); 
} 

struct Range_error : out_of_range { // enhanced vector range error reporting 
    int index; 
    Range_error(int i) :out_of_range("Range error: "+to_string(i)), index(i)  { } 
}; 


// trivially range-checked vector (no iterator checking): 
template< class T> struct Vector : public std::vector<T> { 
    typedef typename std::vector<T>::size_type size_type; 

    Vector() { } 
    explicit Vector(size_type n) :std::vector<T>(n) {} 
    Vector(size_type n, const T& v) :std::vector<T>(n,v) {} 
    template <class I> 
    Vector(I first, I last) :std::vector<T>(first,last) {} 

    T& operator[](unsigned int i) // rather than return at(i); 
    { 
     if (i<0||this->size()<=i) throw Range_error(i); 
     return std::vector<T>::operator[](i); 
    } 
    const T& operator[](unsigned int i) const 
    { 
     if (i<0||this->size()<=i) throw Range_error(i); 
     return std::vector<T>::operator[](i); 
    } 
}; 

// disgusting macro hack to get a range checked vector: 
#define vector Vector 

// trivially range-checked string (no iterator checking): 
struct String : std::string { 

    String() { } 
    String(const char* p) :std::string(p) {} 
    String(const string& s) :std::string(s) {} 
    template<class S> String(S s) :std::string(s) {} 
    String(int sz, char val) :std::string(sz,val) {} 
    template<class Iter> String(Iter p1, Iter p2) : std::string(p1,p2) { } 

    char& operator[](unsigned int i) // rather than return at(i); 
    { 
     if (i<0||size()<=i) throw Range_error(i); 
     return std::string::operator[](i); 
    } 

    const char& operator[](unsigned int i) const 
    { 
     if (i<0||size()<=i) throw Range_error(i); 
     return std::string::operator[](i); 
    } 
}; 

#ifndef _MSC_VER 
namespace __gnu_cxx { 

    template<> struct hash<String> 
    { 
     size_t operator()(const String& s) const 
     { 
      return hash<std::string>()(s); 
     } 
    }; 

} // of namespace __gnu_cxx 
#endif 


struct Exit : runtime_error { 
    Exit(): runtime_error("Exit") {} 
}; 

// error() simply disguises throws: 
inline void error(const string& s) 
{ 
    throw runtime_error(s); 
} 

inline void error(const string& s, const string& s2) 
{ 
    error(s+s2); 
} 

inline void error(const string& s, int i) 
{ 
    ostringstream os; 
    os << s <<": " << i; 
    error(os.str()); 
} 

#if _MSC_VER<1500 
    // disgusting macro hack to get a range checked string: 
    #define string String 
    // MS C++ 9.0 have a built-in assert for string range check 
    // and uses "std::string" in several places so that macro substitution  fails 
#endif 

template<class T> char* as_bytes(T& i) // needed for binary I/O 
{ 
    void* addr = &i; // get the address of the first byte 
         // of memory used to store the object 
    return static_cast<char*>(addr); // treat that memory as bytes 
} 


inline void keep_window_open() 
{ 
    cin.clear(); 
    cout << "Please enter a character to exit\n"; 
    char ch; 
    cin >> ch; 
    return; 
} 

inline void keep_window_open(string s) 
{ 
    if (s=="") return; 
    cin.clear(); 
    cin.ignore(120,'\n'); 
    for (;;) { 
     cout << "Please enter " << s << " to exit\n"; 
     string ss; 
     while (cin >> ss && ss!=s) 
      cout << "Please enter " << s << " to exit\n"; 
     return; 
    } 
} 



// error function to be used (only) until error() is introduced in Chapter 5: 
inline void simple_error(string s) // write ``error: s?? and exit program 
{ 
    cerr << "error: " << s << '\n'; 
    keep_window_open();  // for some Windows environments 
    exit(1); 
} 

// make std::min() and std::max() accessible: 
#undef min 
#undef max 

#include<iomanip> 
inline ios_base& general(ios_base& b) // to augment fixed and scientific 
{ 
    b.setf(ios_base::fmtflags(0),ios_base::floatfield); 
    return b; 
} 

// run-time checked narrowing cast (type conversion): 
template<class R, class A> R narrow_cast(const A& a) 
{ 
    R r = R(a); 
    if (A(r)!=a) error(string("info loss")); 
    return r; 
} 


inline int randint(int max) { return rand()%max; } 

inline int randint(int min, int max) { return randint(max-min)+min; } 

inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x 

#endif 
+3

Se si utilizza la seconda edizione del libro (si dovrebbe), utilizzare [questa versione] (http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h) dell'intestazione. Se devi utilizzare la prima edizione, aggiungi '#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS' prima di' #include '. –

+5

'Si prega di utilizzare ' è abbastanza esplicito.Il tuo libro è vecchio, trova uno migliore o continua a guidarlo se non ti preoccupi di apprendere tecniche di programmazione obsolete. Dovresti preoccuparti, non ti insegnerà nulla su C++ 11. Questo non è buono. –

risposta

11

Ci sono diversi modi per risolvere il problema. Si potrebbe semplicemente avere il compilatore ignorarlo in Visual Studio scrivendo

#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS 1

nella parte superiore del suo file di intestazione (e probabilmente sarete bene per il resto della sua serie).

È anche possibile riscrivere la sua intestazione in sostituzione di hash_map utilizzando unordered_map. Non lo raccomando dato che sei nuovo nella programmazione, ma una specie di soul su Stack Overflow può farlo per te e puoi copiarlo (non dovrebbe essere affatto difficile). MODIFICA: T.C. lo ha trovato here nella sezione commenti del tuo post.

Infine, è possibile includere solo i file di intestazione necessari per qualsiasi unità che si sta facendo nel libro e scrivere manualmente le funzioni che sta utilizzando come necessario. In questo caso per accedere alla funzione cout devi scrivere #include <iostream> nella parte superiore del file, quindi scrivere anche using namespace std; prima del tuo int main(). In alternativa, è possibile scrivere std::cout << "Hello World!"; senza includere using namespace std;, è tutto ciò che fa. Il prodotto finale sarà simile:

#include <iostream> //for learning, it's probably better to know what each header file does before you use it. silly book. 
using namespace std; //act like std:: is before function calls from that library 
int main()        //C++ programs start by executing the function main 
{ 
    cout <<"Hello, World!\n"; //output "Hello, World!" 
    cin.get();   //wait for a return character to be entered 
    return 0; 
} 

Vedendo quanto a come stai scrivendo su Stack Overflow per cominciare e probabilmente hanno un attitudine alto per imparare C++, vi consiglio di fare il secondo e cercando di vedere esattamente quali sono le sue funzioni stai facendo una volta arrivato nel suo libro e dopo fai una rapida ricerca su internet per qualsiasi cosa interessante che vuoi imparare.

+2

unordered_map è abbastanza vicino a una sostituzione diretta drop-in per hash_map. Una semplice ricerca e sostituzione dovrebbe andare bene. – Puppy

+0

@Puppy dato che c'è '#define unordered_map hash_map', potrebbe essere * molto facile * fare proprio questo – Caleth

0

Penso che la soluzione migliore per il problema specifico dell'OP sia scaricare la versione aggiornata di std_lib_facilities.hhere. Il nuovo file utilizza unordered_map anziché hash_map.

Nota: questa soluzione è stata già suggerita da T.C. nei commenti ed è anche menzionato da qualche parte nella risposta di TheSmartWon. Ho scritto una nuova risposta solo perché probabilmente è più facile per gli altri utenti scoprire le informazioni qui.

Problemi correlati