Note that there are some explanatory texts on larger screens.

plurals
  1. POSegmentation Fault - vector string - multimap implementation
    primarykey
    data
    text
    <p>I try to make this implementation of a multimap in C++, but I run into a seg fault when trying to access the vector "values", even though values.size() returns the correct answer.</p> <p>I know the seg fault happens on line 22, but I don't know why. Would appreciate any help.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string.h&gt; using namespace std; template&lt;class DT1,class DT2&gt; class Pair { public: Pair(DT1 key_in, DT2 value_in) { key = key_in; values.push_back(value_in); } DT1 key; vector&lt;DT2&gt; values; int insert_value(DT2 item) { bool value_found = false; cout &lt;&lt; "values size "&lt;&lt;values.size() &lt;&lt; endl; cout &lt;&lt; "test " &lt;&lt; values[0] &lt;&lt; endl; for (unsigned int i = 0; i &lt; values.size(); i++) { cout &lt;&lt;"i " &lt;&lt; i &lt;&lt; endl; if (values[i] == item) value_found = true; } if (value_found == false) { cout&lt;&lt;"not found"&lt;&lt;endl; values.push_back(item); } return 0; } }; template&lt;class T1, class T2&gt; class MultiMap { public: MultiMap() {}; vector&lt;Pair&lt;T1, T2&gt; &gt; pair_container; int insert(T1 key_in, T2 value_in) { bool key_found = false; unsigned int i; for (i = 0; i &lt; pair_container.size(); i++) { if (pair_container[i].key == key_in) key_found = true; } if (key_found == false) pair_container.push_back(Pair&lt;T1,T2&gt;(key_in, value_in)); if (key_found == true) { pair_container[i].insert_value(value_in); // seg fault } return 0; } }; int main() { MultiMap&lt;char, string&gt; Map1; Map1.insert('a', "anchor"); cout &lt;&lt; Map1.pair_container[0].values[0] &lt;&lt; endl; Map1.insert('a', "application"); // seg fault cout &lt;&lt; "hello!"&lt;&lt;endl; Map1.insert('b', "boolean"); 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.
 

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