2016-11-12 74 views
0

这里是我得到的错误: Exercise11.cxx:29:13:错误:无效的操作数的二进制表达式(“ostream的”(又名“basic_ostream”)和“载体”)错误消息/矢量

#include <iostream> 
#include <vector> 
#include <iomanip> 

using namespace std; 
int main() 
{ 
    cout << "Kaitlin Stevers" << endl; 
    cout << "Exercise 11 - Vectors" << endl; 
    cout << "November 12, 2016" <<endl; 
    cout << endl; 
    cout << endl; 
    int size; 
    cout << " How many numbers would you like the vector to hold? " << endl; 
    cin >> size; 
    vector<int> numbers; 
    int bnumbers; 

    for (int count = 0; count < size; count++) 
    { 
     cout << "Enter a number: " << endl; 
     cin >> bnumbers; 
     numbers.push_back(bnumbers); 
    } 
    //display the numbers stored in order 
    cout << "The numbers in order are: " << endl; 
    for(int i=0; i < size; i++) 
    { 
     cout<<numbers[i]<< " "; 
    } 
    cout << endl; 
    return 0; 
} 

的错误出现在代码的一部分,上面写着:

cout << numbers << endl; 

第二个问题:

如何使用vent.reverse();反转矢量然后显示它。

回答

1

你必须使用一个循环输出向量:

for(int i=0; i < size; i++){ 
    cout<<numbers[i]<< " "; 
} 
+0

完美。谢谢,这工作! –

1

错误告诉你所有你需要知道的:operator<<没有被定义在std::coutstd::vector之间。

失败是这一行...

cout << numbers << endl; 

...因为coutostreamnumbersvectorHere's a list of supported types that can be streamed into ostream.


考虑使用for循环打印出的numbers内容:

cout << "The numbers in order are: " << endl; 

for(const auto& x : numbers) 
{ 
    cout << x << " "; 
} 

cout << endl; 

如果您没有访问C++ 11的特点,认真考虑他们研究和更新你的编译器。下面的代码,如果C++ 03兼容:

cout << "The numbers in order are: " << endl; 

for(std::size_t i = 0; i < numbers.size(); ++i) 
{ 
    cout << numbers[i] << " "; 
} 

cout << endl; 
+0

什么是 '常量汽车及'? –

+1

看看['auto'](http://en.cppreference.com/w/cpp/language/auto)和[range'for'](http://en.cppreference.com/w/cpp/language /范围换)。它们都是C++ 11的特性。 –

+0

我使用了该代码,并得到了以下错误:Exercise11.cxx:27:15:warning:'auto'类型说明符是C++ 11扩展名[-WC++ 11-extensions] –

1

你不能叫cout << numbers因为输出没有定义的方式的载体。如果要打印出矢量中的数据,则需要遍历并分别打印每个元素。更多信息,请How to print out the contents of a vector?

1

的另一种方法,使用C++ 11层的功能

for (auto it = numbers.begin(); it < numbers.end(); it ++) 
    cout << (*it) << "\t";