这是我得到的错误: Exercise11.cxx:29:13:错误:二进制表达式的操作数无效(' ostream'(又名' basic_ostream')和' vector')
#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();反转矢量然后显示它。
答案 0 :(得分:1)
错误告诉您需要知道的所有内容:operator<<
和std::cout
之间未定义std::vector
。
失败的一行就是这一行......
cout << numbers << endl;
...因为cout
是ostream
而numbers
是vector
。 Here'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;
答案 1 :(得分:1)
您无法调用cout << numbers
,因为没有定义的方法来输出矢量。如果要打印出矢量中的数据,则需要迭代并分别打印每个元素。有关详细信息How to print out the contents of a vector?
答案 2 :(得分:1)
您必须使用循环来打印矢量:
for(int i=0; i < size; i++){
cout<<numbers[i]<< " ";
}
答案 3 :(得分:1)
另一种方法,使用C ++ 11功能
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container);
ArrayList<String> weekForecast = new ArrayList<>();
weekForecast.add("Today - Sunny - 88/63");
weekForecast.add("Tomorrow - Foggy - 70/40");
weekForecast.add("Weds - Cloudy - 72/63");
weekForecast.add("Thurs - Asteroids - 75/65");
weekForecast.add("Fri - Heavy Rain - 65/56");
weekForecast.add("Sat - HELP TRAPPED IN WEATHERSTATION - 60/51");
weekForecast.add("Sun - Sunny - 80/68");
mForecastAdapter = new ArrayAdapter<>(getActivity(),
R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
//return inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}