我在堆中有一个向量,但无法获取其元素 - 它不会编译 - 给出n错误'无法绑定'std :: basic ostream'堆栈向量和简单数组工作正常。这有什么不对?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> * factors= new vector<int>(4);
cout<<factors<<endl;
cout<<(factors+1)<<endl;
//cout<<factors[1]<<endl;
factors->push_back(12);
factors->push_back(232);
factors->push_back(54);
factors->push_back(42);
//cout<<*factors; //error - cannot bind 'std::ostream..' lvalue to 'std::basic_ostream...'
// cout<<factors[0]; // error
//vector in stack
vector<int> factors3(4);
factors3.push_back(43);
factors3.push_back(543);
factors3.push_back(64);
factors3.push_back(26);
cout<<"factors3 "<<factors3[3]<<endl; //gives "0"
cout<<"factors3 "<<factors3.at(3)<<endl; //gives "0"
int * factors2=new int[10];
factors2[0]=32;
factors2[1]=35;
factors2[2]=676;
factors2[3]=123;
cout<<factors2[0]<<endl; //it's OK
cout<<factors2[1]<<endl;
cout<<*factors2<<endl;
cout << "Done" << endl;
return 0;
}
答案 0 :(得分:3)
cout<<(factors+1)<<endl; //cout<<factors[1]<<endl;
应该是:
cout << (*factors)[1] << endl;
vector<int> factors3(4); factors3.push_back(43); factors3.push_back(543); factors3.push_back(64); factors3.push_back(26); cout<<"factors3 "<<factors3[3]<<endl; //gives "0" cout<<"factors3 "<<factors3.at(3)<<endl; //gives "0"
因为您创建了一个包含4个元素的向量,然后再推送4个元素,所以您最终会得到一个带有元素0, 0, 0, 0, 43, 543, 64, 26
的向量
答案 1 :(得分:3)
让我们看看导致编译器错误的行。首先,这一个:
cout << *factors << endl;
此处factors
为vector<int>*
,因此*factors
为vector<int>
。因此,此代码尝试将vector<int>
插入到流中。您不能使用<<
运算符在C ++中显示vector<int>
(它没有带有重载的<<
运算符),因此您在这里遇到的编译器错误意味着“我看到您尝试使用<<
输出vector
,但我不知道该怎么做。“
您可能想知道为什么代码
cout << *factors2 << endl;
正常工作。在这种情况下,factors2
是int*
,因此当您通过编写factors2
取消引用*factors2
时,您将获得一个真实的诚实整数,确实打印出来了。请注意,原始数组和vector
在这方面的工作方式不同 - 在C ++中,指向数组的指针只是指向数组第一个元素的指针,因此取消引用它们会产生指向第一个元素的指针,而指向a的指针则指向第一个元素。 vector
不与指向其第一个元素的指针相同。
这也解释了写作的原因
cout << factors[0] << endl;
不起作用。请记住 - factors
是指向vector
的指针,而vector
不是数组。写factors[0]
表示“给我vector
所指向的数组中的第一个factors
,而不是”给我{{1}所指向的vector
的第一个元素如果这就是你想要做的,你可以写
factors
这表示“取消引用cout << (*factors)[0] << endl;
以取回实际的factors
,然后查找其第0个元素。”
至于你的第二个问题 - 你为什么不看到你添加到矢量中的数字? - 注意你通过写
声明了向量vector
vector<int> factors3(4); // <--- Notice the 4
这里的意思是“给我(4)
初始化,有四个vector
,所有这些都是零。”然后,当您使用int
时,您将向push_back
添加新元素,而不是替换现有元素。你可以通过直接写入向量元素来解决这个问题:
vector
或未指定vector<int> factors3(4);
factors3[0] = 43;
factors3[1] = 543;
factors3[2] = 64;
factors3[3] = 26;
的尺寸:
factors3
或者,如果你有一个现代编译器,通过初始化这样的向量:
vector<int> factors3; // <--- No 4!
factors3.push_back(43);
factors3.push_back(543);
factors3.push_back(64);
factors3.push_back(26);
无论哪种方式,你都在混合和匹配两种不同的方法 - 每种方法都可以单独工作 - 但这些方法并不符合你的期望。
总结:
vector<int> factors3 = {43, 545, 64, 26};
- 这是一个很容易犯的错误。