문제 설명
벡터 벡터에서 하위 벡터의 첫 번째 값을 찾기 위해 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
.