vector :: insert segmentation fault [英] vector::insert segmentation fault
问题描述
我有这样的类:
classA
{
public:
classA()
{
//这里我做了一些事情,但没有涉及到向量
}
void updateVec(int idx,int value)
{
//这里,我想更新向量向量基于args传递
myVec.insert(myVec.begin()+ idx,value);
}
std :: vector< int> myVec;
}
现在,我在insert语句中得到分段错误。我需要在某个地方初始化向量吗?
似乎没有正确初始化。
初始化用作本地var
创建一个大小为3,初始化为0的ints的向量
std :: vector
如何在类的构造函数中初始化/ b>
#include< iostream>
#include< vector>
class A {
public:
A(int size);
〜A();
void updateVec(int idx,int value);
void print();
private:
std :: vector< int> myVec;
};
A :: A(int size){
myVec.resize(size);
}
A ::〜A(){
}
void A :: updateVec(int idx,int value){
myVec.insert(myVec.begin()+ idx,value);
}
void A :: print(){
std :: vector< int> :: iterator it;
for(it = myVec.begin(); it!= myVec.end(); it ++){
std :: cout< < *它;
}
}
int main(){
A * a = new A(10);
a-> updateVec(2,10);
a-> print();
}
这里是关于如何在C ++中使用向量的文档/ >
http://www.cplusplus.com/reference/stl/vector / insert /
I have a class like this:
classA
{
public:
classA()
{
//Here I am doing something but nothing related to vector
}
void updateVec(int idx, int value)
{
//Here, I want to update vector vector based on args passed
myVec.insert(myVec.begin() + idx, value);
}
std::vector<int> myVec;
}
Now, I am getting segmentation fault on insert statement. Do I need to initialize vector somewhere?
From your code it seems that you did not initialize it properly.
initialization for use as local var
Create a vector of ints, size 3, initialized to 0
std::vector<int> myvector (3,0);
Short example of how to initialize(and then resize) a vector in a class's constructor
#include <iostream>
#include <vector>
class A {
public:
A(int size);
~A();
void updateVec(int idx, int value);
void print();
private:
std::vector<int> myVec;
};
A::A(int size) {
myVec.resize(size);
}
A::~A() {
}
void A::updateVec(int idx, int value) {
myVec.insert(myVec.begin() + idx, value);
}
void A::print() {
std::vector<int>::iterator it;
for (it=myVec.begin(); it!=myVec.end(); it++) {
std::cout << " " << *it;
}
}
int main() {
A* a = new A(10);
a->updateVec(2,10);
a->print();
}
Here is documentation/example on how to use a vector in C++
http://www.cplusplus.com/reference/stl/vector/insert/
这篇关于vector :: insert segmentation fault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!