ProgramingTip

C ++에서 std :: 벡터 확인

bestdevel 2020. 11. 22. 20:22
반응형

C ++에서 std :: 벡터 확인 특정 값을 포함


이 질문에 이미 답변이 있습니다.

내 벡터에 특정 요소가 포함되어 있는지 여부를 알려주는 내장 함수가 있습니까?

std::vector<string> v;
v.push_back("abc");
v.push_back("xyz");

if (v.contains("abc")) // I am looking for one such feature, is there any
                       // such function or i need to loop through whole vector?

std::find다음과 같이 사용할 수 있습니다 .

if (std::find(v.begin(), v.end(), "abc") != v.end())
{
  // Element in vector.
}

사용할 수 있으려면 std::find: include <algorithm>.


  1. 컨테이너에 고유 한 값만 포함 된 경우 대신 사용하는 것이 좋습니다. 로그 작성으로 집합 멤버십을 쿼리 할 수 ​​있습니다.std::set

    std::set<std::string> s;
    s.insert("abc");
    s.insert("xyz");
    if (s.find("abc") != s.end()) { ...
    
  2. 벡터가 정렬 된 상태로 유지되는 경우를 사용 하면 즉시 로그도 제공됩니다.std::binary_search

  3. 다른 모든 방법이 실패하면 단순 선형 검색 인로 폴백하십시오 .std::find


C ++ 11에서는 std::any_of대신 사용할 수 있습니다 .

배열에 0이 있는지 확인하는 예 :

std::array<int,3> foo = {0,1,-1};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i==0;}) )
std::cout << "zero found...";

<algorithm>있으며 std::find.


std::find().

참고 URL : https://stackoverflow.com/questions/6277646/in-c-check-if-stdvectorstring-contains-a-certain-value

반응형