[英]Using 'lower_bound'
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
int n, m;
cin >> n >> m;
long int ar[n];
for (int j = 0; j < n; ++j) cin >> ar[j];
vector<long> v(ar, ar+n);
sort(v.begin(), v.end());
for (int k = 0; k < m; ++k) {
long b;
cin >> b;
if (binary_search(v.begin(), v.end(), b)) cout << "YES" << endl;
else {
vector<int>::iterator it;
it=lower_bound(v.begin(), v.end(), b);
v.insert(it-v.begin(), b);
cout << "NO" << endl;
}
}
}
return 0;
}
編譯器在'it = lower_bound(______)'和'(it-v.begin(),b)'處顯示錯誤。 我聽不懂 請幫助我解決這個問題。
[Error] no match for 'operator=' (operand types are 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' and '__gnu_cxx::__normal_iterator<long int*, std::vector<long int> >')
[Error] no match for 'operator-' (operand types are 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' and 'std::vector<long int>::iterator {aka __gnu_cxx::__normal_iterator<long int*, std::vector<long int> >}')
通過錯誤消息,可以更輕松地找到錯誤。
[Error] no match for 'operator=' (operand types are 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' and '__gnu_cxx::__normal_iterator<long int*, std::vector<long int> >')
您的類型不匹配。 一個迭代器進入vector<int>
,另一個進入vector<long>
。 看到:
vector<long> v(ar, ar+n); // the vector you declare.
vector<int>::iterator it; // the iterator you want to save the element location in.
您必須在這里決定一種類型。 您有int
或long
的嗎?
您的insert
請求也有誤。 第一個參數不應像您似乎想的那樣是索引,它應該是您要插入它的位置的迭代器。 所以就這樣稱呼它:
v.insert(it, b); // we don't have to subtract `v.begin()`.
睡一會兒再看一遍,這里還有一些其他評論。
cin >> n >> m;
long int ar[n];
在這里,您可以從輸入中讀取數組的大小。 這是一個編譯器擴展,不是標准的C ++。 在C ++中,在編譯時必須知道數組的大小。 使用std::vector
代替。 您已經使用它了。
long int ar[n];
for (int j = 0; j < n; ++j) cin >> ar[j];
vector<long> v(ar, ar+n);
無論如何,當您使用std::vector
,就不需要該數組。 特別是因為它利用了我上面所說的編譯器擴展。 更改為
vector<long> v(n);
for (int j = 0; j < n; ++j) cin >> v[j];
最后但並非最不重要的一點是使用更好的變量名。 您所有的變量均為1或2個字符長。 這使得即使遵循相對較少的行數也很難遵循代碼,並且一旦代碼變大,就變得絕對可怕。 沒有理由在C ++中使用這樣的簡短變量名,而使用更長的描述性變量名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.