Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is so much wrong with this code that I don't know where to start...</p> <ul> <li>use std::string</li> <li>use a std::map to associate int values with the strings. This will pretty much already do what you want.</li> <li>don't call the destructor for anything that was not new'd. To delete something use delete/delete[] and don't call the destructor directly. If you do use new, use the RAII idiom using managing objects such as std::unique_ptr or std::shared_ptr to avoid having to manually call delete/delete[] and to write exception safe code</li> </ul> <p>Here is a somewhat improved version. Notice that there is not a single call to new/delete.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;map&gt; #include &lt;cstdio&gt; class list { public: explicit list( std::string n ) : name( n ) {} ~list() { std::cout &lt;&lt; "~list:" &lt;&lt; name &lt;&lt; std::endl; } void list::insert(int number, std::string const&amp; txt ){ items.insert( std::make_pair(number,txt)); } void list::remove(int number){ items.erase( number ); } void print( ){ std::cout &lt;&lt; name &lt;&lt; ";" &lt;&lt; std::endl; for( Items::const_iterator it = items.begin(), end = items.end(); it != end; ++it ) { std::cout &lt;&lt; "num: " &lt;&lt; it-&gt;first &lt;&lt; " | " &lt;&lt; "txt: " &lt;&lt; it-&gt;second &lt;&lt; std::endl; } std::cout &lt;&lt; std::endl; } private: typedef std::map&lt;int,std::string&gt; Items; Items items; std::string name; }; int main() { list l1( "lista1" ); l1.insert( 5, "Endian"); l1.insert( 7, "Endianness"); l1.insert( 100, "Hexediting"); l1.insert( 34, ".mil"); // extra scope so the destructor of l2 is called before call to getchar { list l2( l1 ); l2.remove( 5 ); l2.print(); } l1.print(); getchar(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload