C++ 向量的主成分
决定了,谢谢大家。向量需要初始化 我是C++新手。如果您能帮我打印以下向量v的内容,我将不胜感激。代码如下:C++ 向量的主成分,c++,vector,C++,Vector,决定了,谢谢大家。向量需要初始化 我是C++新手。如果您能帮我打印以下向量v的内容,我将不胜感激。代码如下: #include <stdio.h> #include <vector> #include <iostream> int main(int argc, char **argv) { std::cout << "hello world\n"; std::vector<int>* v; (<-- s
#include <stdio.h>
#include <vector>
#include <iostream>
int main(int argc, char **argv)
{
std::cout << "hello world\n";
std::vector<int>* v; (<-- std::vector<int>* v = new std::vector<int>();]
v->push_back(17);
v->push_back(12);
v->push_back(23);
v->push_back(42);
for(std::vector<int>::iterator it = v->begin(); it!= v->end(); ++it) {
std::cout << *it << "\n";
}
std::cout <<"done\n";
return 0;
}
#包括
#包括
#包括
int main(int argc,字符**argv)
{
标准:不能向后推(12);
v->推回(23);
v->推回(42);
对于(std::vector::iterator it=v->begin();it!=v->end();++it){
std::cout您没有为向量指针分配内存。我建议只使用堆栈上分配的变量:
#include <stdio.h>
#include <vector>
#include <iostream>
int main(int argc, char **argv)
{
std::cout << "hello world\n";
std::vector<int> v; // <<<<< Note that * was omitted here
v.push_back(17);
v.push_back(12);
v.push_back(23);
v.push_back(42);
for(std::vector<int>::iterator it = v.begin(); it!= v.end(); ++it) {
std::cout << *it << "\n";
}
std::cout <<"done\n";
return 0;
}
#包括
#包括
#包括
int main(int argc,字符**argv)
{
std::cout无需在此处设置v
指针,请使用类似以下内容:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> v;
// push_back data...
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout,","));
}
我假设这不是真正的代码,因为在这种情况下没有很好的理由使用指向向量的指针,而且指针不指向任何东西
但是,如果您的问题只是如何打印给定指针的向量的内容,那么您可以简单地取消对指针的引用并使用基于范围的for循环
#include <vector>
#include <iostream>
void print(std::vector<int>* v) {
for(int value : *v)
std::cout << value << "\n";
}
int main() {
std::cout << "hello world\n";
std::vector<int> v = {17, 12, 23, 42};
print(&v);
std::cout <<"done\n";
}
#包括
#包括
无效打印(标准::矢量*v){
对于(整数值:*v)
std::cout为什么v
是指针?@Kevin,准确地说是无效指针。它是另一个程序中的指针,我需要打印出来。原始的是vector*我想你误解了。为什么它是指向向量的指针而不是向量本身?@crownLearnig-如果你真的想使用指针,你应该用new来分配它<代码> >代码>删除<代码>?在2016?@ ArchbishopOfBanterbury,嗯,我真的必须在2016给你讲授C++中的内存管理吗?在Web上不缺少这些材料。@米莎·瓦伦蒂亚克:当然,当然,但是假设为 Advutix<代码>提供的OP函数签名是不能更改的库的一部分。那么普通指针是这里唯一的选项:)@archbishopfanterbury,这是为什么?您当然可以将指向托管对象的指针(在堆栈上或智能指针中)传递给函数。问题在于使用原始指针作为对象的所有者。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> v;
// push_back data...
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout,","));
}
int main() {
std::vector<int>* v = new std::vector<int>(); // allocate memory on heap
v->push_back(17);
// etc...
std::copy(v->begin(), v->end(), std::ostream_iterator<int>(std::cout,","));
delete v; // make sure to delete from heap to prevent memory leak
}
#include <vector>
#include <iostream>
void print(std::vector<int>* v) {
for(int value : *v)
std::cout << value << "\n";
}
int main() {
std::cout << "hello world\n";
std::vector<int> v = {17, 12, 23, 42};
print(&v);
std::cout <<"done\n";
}