Which one cause std::bad_alloc

Thx
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
class Solution {
    
public:
    vector<string> solution;
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        
        solution.reserve(tickets.size());
        solution.push_back("JFK");
        while (!tickets.empty()) {
            int tgt = -1;
            for (int i = 0; i < tickets.size(); ++i)
            {
                if (!tickets[i].first.compare(solution[solution.size()-1])) {
                    if (tgt == -1) {
                        tgt = i;
                    } else if (tickets[tgt].second.compare(tickets[i].second) > 0) {
                        tgt = i;
                    }
                }
            }
            solution.push_back(tickets[tgt].second);
            tickets.erase(tickets.begin()+tgt);
        }
        
        return solution;
    }
    
};
The scope of solution is incorrect.

Your bad_alloc can happen in solution.reserve() or in the creation of tickets.. However, you're wasting memory by passing tickets by value.
Last edited on
Topic archived. No new replies allowed.