Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I access a std::vector<std::pair<std::string, std::string>> through vec[i].first()?

I am attempting to print data from a std::vector<std::pair<std::string,std::string>> via a for loop. MSVC says that I can’t call make a call through this vector. I tried it with std::vector<std::pair<int, int>> as well and got the same error. I tried iterating with a for loop on a std::vector<int> and it worked fine. I haven’t tried on another compiler.

Sample code

    std::vector<std::pair<std::string, std::string>> header_data = get_png_header_data(file_contents);

    for (unsigned int i = 0; i < header_data.size(); i++)
    {
        std::cout << header_data[i].first(); //throws an error on this line "call of an object of a class type without an appropriate operator() or conversion functions to pointer-to-function type
    }

I would appreciate an alternative way to access my vector or another storage type that I could use.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks 🙂

>Solution :

Your std::pair is basically (in a manner of speaking):

    struct std::pair {
        std::string first;
        std::string second;
    };

That’s what std::pairs are. first and second are ordinary class members, not methods/functions. Now you can easily see what’s happening: .first() attempts to call first‘s () operator overload. Obviously, std::strings have no such overloads. That’s what your C++ compiler’s error message is telling you. If you reread your compiler’s error message it now becomes crystal clear.

You obviously meant to write std::cout << header_data[i].first;.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading