Cpp-Primer icon indicating copy to clipboard operation
Cpp-Primer copied to clipboard

Exercise 9.22: segment fault

Open zzb610 opened this issue 5 years ago • 1 comments

when vector iv = {1, 2, 3, 2, 5, 7, 8, 9, 10}; get segment fault

zzb610 avatar Oct 15 '19 03:10 zzb610

Hi ycbw, I tried the vector you mentioned and the code is like below: #include #include

void double_and_insert(std::vector& v, int some_val) { auto mid = [&]{ return v.begin() + v.size() / 2; }; for (auto curr = v.begin(); curr != mid(); ++curr) if (*curr == some_val) ++(curr = v.insert(curr, 2 * some_val)); }

int main() { std::vector v{ 1, 2, 3, 2, 5, 7, 8, 9, 10}; double_and_insert(v, 1);

for (auto i : v)
    std::cout << i << std::endl;

}

It ran as expected. You may have a wrong vector name, instead of "iv", you should use "v".

zhaozhangjian avatar Jan 17 '20 07:01 zhaozhangjian