티스토리 뷰
적절한 예시인지는 모르겠다만 leetcode 문제를 풀다가 뜬금포로 lambda 를 써보고 싶다는 생각이 들었다.
lambda 함수를 왜쓰냐? 라고 한다면 아래의 글을 한번쯤 읽어보면 좋을 거 같다.
https://www.cppstories.com/2020/05/lambdasadvantages.html/
5 Advantages of C++ Lambda Expressions and How They Make Your Code Better
[](){} The mixture of brackets in the preceding line become one of the most noticeable indications of Modern C++. Yep. Lambda Expressions! It might sound like I’m trying to create a new blog post about something that everyone knows. Is that true? Do you
www.cppstories.com
개인적으로 2번의 이유(코드의 locality를 높인다)에는 바로 납득이 갔다. 대개 읽기 편했던 논문은 표나 그림을 언급할때 그 근처에 표랑 그림이 찾기 쉽게 위치해있다. 그렇지 않다면, 이 문장 읽다가 앞 페이지로, 뒤 페이지로 종이를 넘겨가거나 pdf 페이지를 넘겨야되는데 이런 거 하나하나가 체력 소비가 많이 된다. 코드도 마찬가지로 특정 함수에서 쓰이는 함수가 저~~~기에 있고 쯔으어어어어~기에 있으면 새삼 코드가 읽기 싫어지는데, lamda 함수를 적절하게 잘쓰면 이런 불편함을 줄일 수 있을 거 같다. 모르고 보면 도대체 이게 내가 알던 c++이 맞아? 싶다. ㅜㅜ
내가 풀던 문제는 아래 문제이다.
https://leetcode.com/problems/word-search/
Word Search - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
먼저 내가 구현했던 코드는 아래와 같다.
class Solution {
public:
vector<vector<char>> board;
string word;
bool dfs(int r, int c, int i)
{
if(r < 0 or r >= board.size()) return false;
if(c < 0 or c >= board[0].size()) return false;
if(word[i] != board[r][c]) return false;
i += 1;
if(i == word.size()) return true;
auto temp = board[r][c];
board[r][c] = '-';//visited
bool ret = dfs(r+1, c, i) or dfs(r, c+1, i) or dfs(r-1, c, i) or dfs(r, c-1, i);
board[r][c] = temp;//reset
return ret;
}
bool exist(vector<vector<char>>& board, string word) {
this->board = move(board);
this->word = move(word);
for(int i=0; i<this->board.size(); i++)
{
for(int j=0; j<this->board[0].size(); j++)
{
if(dfs(i, j, 0))
{
return true;
}
}
}
return false;
}
};
먼저 구현하면서 스스로 상당히 열받았던 부분은 dfs 함수에서 exist 함수의 입력 인자인 board와 word를 접근하기위해 멤버변수를 solution 클래스에 선언한 부분이였다.
함수의 입력인자인 board와 word를 멤버 변수 board와 word로 카피하는 과정에서 최대한 카피하는데 드는 비용을 줄이고자 std::move를 사용했다. 근데... 애초에 board와 word를 따로 멤버변수로 한 번 더 만들어주는게 너무 너무 마음에 안든다. 그렇다고 dfs 함수에 call by reference 로 board와 word까지 넘겨주자니 것도 마음에 안든다. 그리고 std::move를 써놓고서 다시 함수 인자로 들어온 board와 word로 move 해주는 과정도 없다. 단순히 문제 통과만하는거면 신경쓸부분은 아니긴 하지만...
내가 원하는건 dfs함수에 함수 인자로 board와 word를 넘기지 않고, 또 멤버변수로도 board와 word를 선언하지 않는 것이다. 이를 위해 lambda를 써서 내가 이루고자하는 목적을 이루었다.
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
function<bool(int, int, int)> dfs = [&](int r, int c, int i) -> bool
{
if(r < 0 or r >= board.size()) return false;
if(c < 0 or c >= board[0].size()) return false;
if(word[i] != board[r][c]) return false;
i += 1;
if(i == word.size()) return true;
auto temp = board[r][c];
board[r][c] = '-';//visited
bool ret = dfs(r+1, c, i) or dfs(r, c+1, i) or dfs(r-1, c, i) or dfs(r, c-1, i);
board[r][c] = temp;//reset
return ret;
};
for(int i=0; i<board.size(); i++)
{
for(int j=0; j<board[0].size(); j++)
{
if(dfs(i, j, 0))
{
return true;
}
}
}
return false;
}
};- Total
- Today
- Yesterday
- C++ Deploy
- 문제집
- 단축키
- 백트래킹
- 가장 긴 증가하는 부분 수열
- 이분탐색
- FairMOT
- MOT
- ㅂ
- 백준
- 파이참
- 백준 11053
- 백준 1766
- LCA
- 위상 정렬 알고리즘
- 자료구조
- PyCharm
- 순열
- 조합
- Lowest Common Ancestor
- 백준 11437
- cosine
- 인공지능을 위한 선형대수
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
