벡터 벡터에서 하위 벡터의 첫 번째 값을 찾기 위해 begin() 및 end() 반복기의 범위를 지정하는 방법은 무엇입니까? (How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors?)


문제 설명

벡터 벡터에서 하위 벡터의 첫 번째 값을 찾기 위해 begin() 및 end() 반복기의 범위를 지정하는 방법은 무엇입니까? (How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors?)

안녕하세요. 저는 벡터 및 STL의 다른 부분으로 작업하는 것이 처음입니다. 도움이 필요합니다. 각 하위 벡터의 인덱스에 주제를 포함하는 문자열 벡터의 벡터가 있습니다(예: arr[1][ 0] = "topic1", "topic1"과 관련된 메시지를 포함하는 arr[1][1..n],

topicID의 값을 찾으려면 topic, 나는 begin() 및 end() 반복자와 함께 find()를 사용하고 일치가 이루어질 때까지 모든 값을 효과적으로 검사합니다. 주제가 항상 arr[i][0]에 있다는 것을 알기 때문에 이것은 매우 비효율적입니다. 주제에 n개의 메시지가 있으면 복잡성이 악화됩니다.

내 현재 접근 방식은 아래와 같습니다. arr[i][0]의 요소만 arr 길이로 확인하려면 이것을 어떻게 리팩토링합니까?

int getTopicID(vector< vector<string> >& arr, string topic)
{
    int topicID = 0;
    for (size_t m = 1; m < arr.size(); ++m)
    {
        auto i = find(arr[m].begin(), arr[m].end(), topic); 
        if (arr[m].end() != i) { topicID = m; break; }
        else { topicID = 0;}
    }
    return topicID;
} 

도움을 주셔서 감사합니다.)


참조 솔루션

방법 1:

How can I refactor this to check only the element at arr[i][0] for the length of arr?

Simply don't loop over all of the elements (std::find being the unnecessary inner loop). Replace body of the outer loop with:

if (arr[m][0] == topic) {
    return m;
}

and after the loop:

return 0;

P.S. You can replace the outer loop with std::find_if.

(by Ben Webbeerorika)

참조 문서

  1. How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors? (CC BY‑SA 2.5/3.0/4.0)

#C++ #vector #arrays #stl






관련 질문

파일의 암호화/복호화? (Encryption/ Decryption of a file?)

이상한 범위 확인 연산자가 있는 C++ typedef (C++ typedef with strange scope resolution operator)

개체 배열 매개변수--오류: '문자' 필드에 불완전한 유형이 있습니다. (Object array parameter--error: field ‘letters’ has incomplete type)

C++에서 메모리 삭제 (Deleting memory in c++)

C++ 프로그램을 실행할 수 없습니다. No se ejecuta el programa (C++ i can't run a program. No se ejecuta el programa)

컴파일 시 변수의 이름과 수명 (Name and lifetime of variables at compile time)

control-c 후 Visual Studio 콘솔 프로그램 충돌 (visual studio console program crashes after control-c)

멤버 변수에 std::enable_if 또는 유사한 메서드 사용 (Using std::enable_if or similar method on member variable)

ifstream input_file(filename); (I am receiving an error "no matching function to call" in the line ifstream input_file(filename);)

ESP8266에서 잠시 실행하면 JsonData 크기가 0이 됩니다. (JsonData size becomes zero after awhile of running in ESP8266)

합에 대한 속도 문제(제수의 합) (Speed problem for summation (sum of divisors))

벡터 벡터에서 하위 벡터의 첫 번째 값을 찾기 위해 begin() 및 end() 반복기의 범위를 지정하는 방법은 무엇입니까? (How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors?)







코멘트