错误:类型"const char[8]"和"const char [17]"的操作数无效为二进制"运算符<<

error: invalid operands of types 'const char[8]' and 'const char [17]' to binary 'operator<<'

本文关键字:char lt const 二进制 运算符 无效 类型 错误 操作数      更新时间:2023-10-16

编译器不像我最后的std::cout行。我评论以指定错误发生的位置。我很想听到一些关于这方面的反馈。提前谢谢。

此外,如果您愿意,我想对我坚持编码实践和包含重复算法C++发表一些一般性评论。我知道在我的 std::map 中将该布尔值作为值是没有用的,但不可能映射像 std::map 这样的一维地图。必须添加一个值。

#include <iostream>
#include <map>
#include <vector>
void print_vector(std::vector<int>); 
bool contains_repeats_1(std::vector<int>);
int main() { 
    int arr1[] = {1, 5, 4, 3, -8, 3, 90, -300, 5, 69, 10};
    std::vector<int> vec1(arr1, arr1 + sizeof(arr1)/sizeof(int));
    std::cout << "vec1 =" << std::endl;
    print_vector(vec1); 
    int arr2[] =  {1, 6, 7, 89, 69, 23, 19, 100, 8, 2, 50, 3, 11, 90};              
    std::vector<int> vec2(arr2, arr2 + sizeof(arr2)/sizeof(int));
    std::cout << "vec2 =" << std::endl;
    print_vector(vec2);
    std::cout << "vec1 " << contains_repeats_1(vec1) ? "does" : "doesn't" << " contain repeats" << std::endl;
        // ^^^^^^ ERROR
    return 0;
} 
void print_vector(std::vector<int> V) { 
    std::vector<int>::iterator it = V.begin(); 
    std::cout << "{" << *it;
    while (++it != V.end())
        std::cout << ", " << *it;
        std::cout << "}" << std::endl;  
}

bool contains_repeats_1(std::vector<int> V) { 
    std::map<int,bool> M;
    for (std::vector<int>::iterator it = V.begin(); it != V.end(); it++) {
        if (M.count(*it) == 0) { 
            M.insert(std::pair<int,bool>(*it, true));
        } else {
            return true;         
        }
        return false; 
    }
} 
条件

运算符?:的优先级相当低(低于 << ),因此您需要添加括号。

std::cout << "vec1 " << (contains_repeats_1(vec1) ? "does" : "doesn't") << " contain repeats" << std::endl;

<<的优先级高于?:

std::cout << "vec1 " << (contains_repeats_1(vec1) ? "does" : "doesn't") << " contain repeats" << std::endl;