I am writing a c++ program that counts occurrence of distinct string token in a given file.
I iterate through std::vector to create std::pair of and insert into std::vector>. Then, I used std::sort to sort it in descending order of the second field (int).
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
...
bool compare(const std::pair<std::string, int> &p1, const std::pair<std::string, int> &p2) {
if (p1.second < p2.second) return false;
return true;
}
TC::TC(const std::vector<std::string> &collection) {
...
// iterating through collection with iterator "it", and push_back a pair when unique string found
std::pair<std::string, int> temp = {*it, std::count(collection.begin(), collection.end(), *it)};
counts.push_back(temp);
// calling std::sort to sort descending order of the field "second"
std::sort(counts.begin(), counts.end(), &compare);
Yet, when I test on a sample file (that I can pass as an argument to main), I get segfault. And, from looking into gdb, following shows up,
Breakpoint 2, compare (p1=..., p2=...) at TokenCounter.cc:47
47 if (p1.second < p2.second) {
(gdb) p p1
$14 = (const std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> &) @0x61c520: {first = "namespace", second = 1}
...
Breakpoint 2, compare (p1=..., p2=...) at TokenCounter.cc:47
47 if (p1.second < p2.second) {
(gdb) p p1
$16 = (const std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> &) @0x61c500: {first = {static npos = <optimized out>,
_M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x61ec88 "sep"}}, second = 1}
It appears to me that the field "first" of some pairs went out of scope and became garbage if I am interpreting that "<__gnu_css..... _M_p" correctly. However, I am confused why such would happen since push_back will create a new copy of pair of new string and int. So it should not be garbage. This is my first post and I am still novice in c++, so please let me know if anything doesn't seem clear.
Aucun commentaire:
Enregistrer un commentaire