C++ 打印向量的值
我使用push_back()函数插入这些元素,我想知道 如何打印向量c的内容C++ 打印向量的值,c++,vector,C++,Vector,我使用push_back()函数插入这些元素,我想知道 如何打印向量c的内容 vector<int> c[2]; c[0].push_back(0); c[0].push_back(1); c[1].push_back(2); c[0].push_back(3); 向量c[2]; c[0]。推回(0); c[0]。推回(1); c[1]。推回(2); c[0]。推回(3); 我尝试了for(int I=0;I
vector<int> c[2];
c[0].push_back(0);
c[0].push_back(1);
c[1].push_back(2);
c[0].push_back(3);
向量c[2];
c[0]。推回(0);
c[0]。推回(1);
c[1]。推回(2);
c[0]。推回(3);
我尝试了for(int I=0;Ifor(const auto&vec:c){
用于(常量自动元素:vec)
std::cout每当你看到下面的符号学习向量的时间c[i]
是一个std::vector
,正如编译器所说的那样,除了n
有多大之外,操作符没有过载,你也会调用未定义的行为。(如果它会编译).至于如何解决您的问题,如果您有一个普通的std::vector
对象(变量),您知道如何从中打印元素吗?那么为什么不在显示的循环中使用它?vector c[2]
--您正在声明一个向量数组
。这真的是您想要的吗?它给了我一个错误:错误:请求“c”中的“begin”成员,这是非类类型的“std::vector[2]”查看我编辑并添加了完整示例的帖子
error: no match for 'operator<<' in 'std::cout << c[i]'|
for (const auto & vec : c) {
for (const auto elem : vec)
std::cout << elem << ' ';
std::cout << '\n';
}
constexpr size_t vecLen = 2;
std::vector<int> c[vecLen];
c[0].push_back(0);
c[0].push_back(1);
c[1].push_back(2);
c[0].push_back(3);
for (size_t vecIndex = 0; vecIndex < vecLen; ++vecIndex) {
for (size_t itemIndex = 0; itemIndex < c[vecIndex].size(); ++itemIndex)
std::cout << c[vecIndex][itemIndex] << ' ';
std::cout << '\n';
}
vector<int>::iterator it;
cout << "myvector contains:";
for ( it=myvector.begin() ; it < myvector.end(); it++ )
cout << " " << *it;
cout << endl;
std::vector<int>::const_iterator iter= vec.begin();
for(iter; iter != vec.end(); ++iter)
{
cout<<*iter; //This is what step 2 provides for
}
ostream& operator<<( ostream& os, const vector<int>&)
{
}
cout << "vector from initializer list: " << endl;
vector<int> vi1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cout << "size: " << vi1.size() << endl;
cout << "front: " << vi1.front() << endl;
cout << "back: " << vi1.back() << endl;
// iterator
vector<int>::iterator itbegin = vi1.begin();
vector<int>::iterator itend = vi1.end();
for (auto it = itbegin; it < itend; ++it) {
cout << *it << ' ';
}
cout << endl;
cout << "element at 5: " << vi1[5] << endl;
cout << "element at 5: " << vi1.at(5) << endl;
cout << "range-based for loop:" << endl;
for (int & i : vi1) {
cout << i << ' ';
}
cout << endl;