"C++ 벡터 find()"의 두 판 사이의 차이

11번째 줄: 11번째 줄:
int getIndex(vector<int> v, int value) {
int getIndex(vector<int> v, int value) {
     auto it = find(v.begin(), v.end(), value);
     auto it = find(v.begin(), v.end(), value);
     if (it == v.end()) {
     return it==v.end() ? -1 : it-v.begin();
        return -1;
    }
    return it - v.begin();
}
}


20번째 줄: 17번째 줄:
     vector<int> v = {11, 1, 12, 2};
     vector<int> v = {11, 1, 12, 2};
     cout << getIndex(v, 2) << endl; // 3
     cout << getIndex(v, 2) << endl; // 3
     cout << getIndex(v, 3) << endl; // -1 (not exists)
     cout << getIndex(v, 3) << endl; // -1
}
}
</syntaxhighlight>
</syntaxhighlight>

2023년 9월 17일 (일) 14:53 판

1 개요

C++ 벡터 find()

2 값 위치 확인

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int getIndex(vector<int> v, int value) {
    auto it = find(v.begin(), v.end(), value);
    return it==v.end() ? -1 : it-v.begin();
}

int main() {
    vector<int> v = {11, 1, 12, 2};
    cout << getIndex(v, 2) << endl; // 3
    cout << getIndex(v, 3) << endl; // -1
}

3 값 있는지 확인

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {11, 1, 12, 2};
    cout << (find(v.begin(), v.end(), 2) != v.end()) << endl; // 1 (exists)
    cout << (find(v.begin(), v.end(), 3) != v.end()) << endl; // 0 (not exists)
}

4 같이 보기

5 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}