使用' lower_bound'

时间:2015-06-27 02:36:48

标签: c++ vector stl iterator

#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;
}

编译器在&#39; it = lower_bound(______)&#39;和&#39;(it-v.begin(),b)&#39; 。 我无法理解。请帮我整理一下。

[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> >}')

1 个答案:

答案 0 :(得分:1)

使用错误消息可以更容易地找到错误。

[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 ++中使用这样的短变量名,使用更长和描述性的名称。

相关问题