简体   繁体   中英

C++ candidate function not viable

I try to print out an empty vector, but I received the following error:

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:220:20: note: candidate function not viable: no known conversion from 'vector<int>' to 'basic_streambuf<std::basic_ostream<char>::char_type> *' (aka 'basic_streambuf<char> *') for 1st argument
    basic_ostream& operator<<(basic_streambuf<char_type, traits_type>* __sb);
                   ^

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:223:20: note: candidate function not viable: no known conversion from 'vector<int>' to 'std::nullptr_t' for 1st argument
    basic_ostream& operator<<(nullptr_t)

I also tried to do std::cout << vec << std::endl; but it still doesn't work.

Here is my code:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int main() {
    vector <int> vec(5);
    cout << vec << endl;
    return 0;
}

Don't get hung up on the failure to convert to std::nullptr_t . The error basically means there isn't an overload of the output stream operator for your vector type. Thus, you have to implement your own output function for vectors, something like this:

#include <iostream>
#include <string>
#include <vector>

template<typename type_t>
std::ostream& operator<<(std::ostream& os, const std::vector<type_t>& vector)
{
    bool comma = false;
    for (const auto& item : vector)
    {
        if (comma) std::cout << ", ";
        std::cout << item;
        comma = true;
    }
    std::cout << "\n";

    return os;
}

int main() 
{
    std::vector<int> vec{ 1,2,3,4,5 };
    std::cout << vec;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM