开发者

Why does this C++ code fail?

开发者 https://www.devze.com 2022-12-20 12:22 出处:网络
I have the following code #include <iostream> #include <vector> using namespace std; int distance(vector<int>& set1, vector<int>& set2) {

I have the following code

#include <iostream>
#include <vector>

using namespace std;

int distance(vector<int>& set1, vector<int>& set2) {
    int distance = 0;

    unsigned int i1 = 0;
    unsigned int i2 = 0;
    while(i1 < set1.size() && i2 < set2.size()) 开发者_开发技巧{
        if(set1[i1] == set2[i2]) {
            ++i1; ++i2;
        } else {
            ++distance;
            set1[i1] < set2[i2] ? ++i1 : ++i2;
        }
    }

    unsigned int zero = 0;
    distance += std::max(set1.size() - i1, zero) + std::max(set2.size() - i2, zero);
}

int main() {
    vector<vector<int> > frequent_sets;
    vector<int> vector3;
    vector3.push_back(1);vector3.push_back(2);vector3.push_back(3);
    vector<int> vector2;
    vector2.push_back(1);vector2.push_back(2);

    frequent_sets.push_back(vector3);
    frequent_sets.push_back(vector3);
    frequent_sets.push_back(vector2);
    frequent_sets.push_back(vector3);


    for(vector<vector<int> >::iterator itouter = frequent_sets.begin(); itouter != frequent_sets.end(); ++itouter)
        for(vector<vector<int> >::iterator itinner = (itouter + 1); itinner != frequent_sets.end(); ++itinner)
            if(distance(*itinner, *itouter) == 0) {
                cout << "Hey" << endl;
            }
}

When I try to compile I get the error:

make all Building file: ../src/TestIterator.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/TestIterator.d" -MT"src/TestIterator.d" -o"src/TestIterator.o" "../src/TestIterator.cpp" /usr/include/c++/4.3/bits/stl_iterator_base_types.h: In instantiation of 'std::iterator_traits > >': ../src/TestIterator.cpp:50:

instantiated from here /usr/include/c++/4.3/bits/stl_iterator_base_types.h:133: error: no type named 'iterator_category' in 'class std::vector

' make: *** [src/TestIterator.o] Error 1

Why is this? When I replace distance(*itouter, *itinner) == 0 with itinner->size() == itouter->size() the code is compiling and running fine.


Youd distance function is clashing with the one in std. That's why it's usually not recommended to write using namespace std; in your code. Try removing that or renaming your function to something like my_distance.


It is trying to use the distance algorithm defined in namespace std. If you want your distance function to be called use ::distance

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号