【问题标题】:gcc and clang both cannot compile a loop programgcc 和 clang 都无法编译循环程序
【发布时间】:2015-01-05 18:23:15
【问题描述】:

我一直无法使用 gcc 和 clang 来编译这个我为教科书中的练习而编写的简单程序。该程序的目标是从标准输入接受 2 个简单的整数值,然后将这 2 个值打印到标准输出。我写的程序如下:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>

using namespace std;
inline void keep_window_open() {char ch; cin>>ch;}

int main() 
{

  vector<int> vect;
  int number;
  int i = 0 ;
  while (cin >> number && vect.size() < 3) 
    {
    vect.push_back(number);
    }

  cout << vect << '\n';

}  

当我使用 gcc 编译程序时,出现以下错误:

Kohs-MacBook-Pro:Learning_C++ Kohaugustine$ gcc drill_chapter_4_v2.cpp -o drill_chapter_4_v2 -stdlib=libstdc++ -lstdc++
drill_chapter_4_v2.cpp:21:8: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'vector<int>')
  cout << vect << '\n';
  ~~~~ ^  ~~~~

当我尝试使用 clang 时,也会发生同样的错误“二进制表达式的操作数无效”。

有谁知道这里到底是什么问题?

我真的是 C++ 新手,虽然我之前有使用 Python 的经验,但转向 C++ 是非常不同的,而且我还没有参加任何正式的编程入门课程,所以如果这是一个非常重要的课程,请多多包涵简单的问题。我将不胜感激任何帮助前进!

谢谢!

【问题讨论】:

    标签: c++ gcc vector clang


    【解决方案1】:

    您不能像这样打印整个矢量。使用循环:

    for (auto value : vect)
        std::cout << value << ' ';
    

    【讨论】:

      【解决方案2】:

      C++ 标准库中没有operator&lt;&lt;(std::ostream, std::vector&lt;int&gt;)

      可以写一个,比如:

      std::ostream& operator<<(std::ostream& os, std::vector<int> v)
      {
         for(auto i : v)
         {
            os << i << ' ';
         }
         return os;
      }
      

      我应该指出,原位迭代向量是典型的解决方案,所以:

         for(auto i : vect)
         {
            std::cout << i << ' ';
         }
      

      将是我希望在代码中看到的内容。

      【讨论】:

      • 这不是超载UB吗?
      • 我刚刚修复了*i - 应该只是i。不然不知道有什么UB?
      • 其实应该没问题。这是一个问题,是否通过添加此重载您正在向std 命名空间添加一些内容。 “某事”可以包括模板特化,但我不确定重载的位置。我得读书了。
      • 那不适用于所有operator&lt;&lt;(std::ostream&amp;, ...) 吗?这不像我的代码在使用 std::vectorstd::ostream 内部的内部结构...
      【解决方案3】:

      修改这部分代码

        while (cin >> number && vect.size() < 3) 
          {
          vect.push_back(number);
          }
      
        cout << vect << '\n';
      

      以下方式

        while ( vect.size() < 3 && cin >> number  ) 
        {
          vect.push_back( number );
        }
      
        for ( int x : vect ) cout << x << '\n';
      

      至于错误,向量没有operator &lt;&lt;。您应该自己定义它,或者使用如上所示的基于范围的 for 循环自己打印出向量的每个元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多