Segmentation fault (core dumped)

Okay so here's my code:

#include <iostream>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <string>
using namespace std;

// TODO: move to separate .h and .cpp files?
template <typename T>
vector<T> operator+(const vector<T> &A, const vector<T> &B) {
vector<T> AB;
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() ); // add A;
AB.insert( AB.end(), B.begin(), B.end() ); // add B;
return AB;
}

typedef vector<uint> Numbers;
typedef vector<string> Cards;

Numbers getRank(Cards cards) {

string first = cards.front();
Cards rest = Cards(cards.begin()+1, cards.end());

if (first.at(0) == 'J' || first.at(0) == 'Q' || first.at(0) == 'K')
return Numbers( { 10 } ) + getRank(rest);
if (first.at(0) == 'A')
return Numbers( { 1 } ) + getRank(rest);

uint num_first = stoi (first.substr(0));

return Numbers( {num_first} ) + getRank(rest);
}

int main() {

Numbers list = Numbers(getRank( { "5C", "5D", "5H", "5S", "JC" } ));

for( auto i: list)
cout << i << " ";
cout << endl;

return EXIT_SUCCESS;
}


and when I tried to run it, this is the only error that it came up:

Segmentation fault (core dumped)

Any ideas guys :/ ??
Always put your code in the code tag so that we can read it properly

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <string>
using namespace std;

// TODO: move to separate .h and .cpp files?
template <typename T>
vector<T> operator+(const vector<T> &A, const vector<T> &B) {
vector<T> AB;
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() ); // add A;
AB.insert( AB.end(), B.begin(), B.end() ); // add B;
return AB;
}

typedef vector<uint> Numbers;
typedef vector<string> Cards;

Numbers getRank(Cards cards) {

string first = cards.front();
Cards rest = Cards(cards.begin()+1, cards.end());

if (first.at(0) == 'J' || first.at(0) == 'Q' || first.at(0) == 'K')
return Numbers( { 10 } ) + getRank(rest);
if (first.at(0) == 'A')
return Numbers( { 1 } ) + getRank(rest);

uint num_first = stoi (first.substr(0));

return Numbers( {num_first} ) + getRank(rest);
}

int main() {

Numbers list = Numbers(getRank( { "5C", "5D", "5H", "5S", "JC" } ));

for( auto i: list)
cout << i << " ";
cout << endl;

return EXIT_SUCCESS;
}


I havent any specific reason yet but I can see that you returning a lot of local objects and/or temporary objects.
That is a bad idea unless you use std::move, rework that logic and see if it imroves
Last edited on
uhmmmm..how?
never mind. i already solved it :). just added another conditional statement. thanks for the suggestion.
Topic archived. No new replies allowed.