【问题标题】:C++ candidate function not viableC++ 候选函数不可行
【发布时间】:2021-12-31 05:57:41
【问题描述】:

我尝试打印出一个空向量,但收到以下错误:

/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)

我也试过std::cout &lt;&lt; vec &lt;&lt; std::endl;,但还是不行。

这是我的代码:

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

using namespace std;

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

【问题讨论】:

  • 改为for (auto i : vec) { cout &lt;&lt; i &lt;&lt; "\"; }。

标签: c++ vector declaration cout


【解决方案1】:

不要担心无法转换为 std::nullptr_t。该错误基本上意味着您的向量类型的输出流运算符没有过载。因此,您必须为向量实现自己的输出函数,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2010-10-31
    • 2019-08-19
    • 1970-01-01
    • 2014-01-22
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多