C++ 断言语句导致段错误
C++ assert statement causing segfault
我试图理解函子。我从 functors and their uses.
借用并修改了以下程序
#include <iostream>
#include <vector>
#include <assert.h>
#include <algorithm>
/*
* A functor is pretty much just a class which defines the operator().
* That lets you create objects which "look like" a function
**/
struct add_x
{
add_x(int y) : x(y)
{
}
int operator()(int y) const {
return x + y;
}
private:
int x;
};
int main()
{
/* create an instance of the functor class*/
add_x add42(42);
/* and "call" it */
int i = add42(8);
/*and it added 42 to its argument*/
assert(i == 50);
/*assume this contains a bunch of values*/
std::vector<int> in;
std::vector<int> out(in.size());
/*
* Pass a functor to std::transform, which calls the functor on every element
* in the input sequence, and stores the result to the output sequence
*/
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
/*for all i*/
assert(out[i] == (in[i] + 1));
return 0;
}
我在 main() 的第二个断言语句中遇到分段错误。 (assert(out[i] == (in[i] + 1));
)我似乎不明白为什么?
in.size()
将 return 0
因为您还没有添加任何内容。这意味着 out
被初始化为空向量。
out[i]
将尝试访问不存在的向量的第 51 个元素(因为 STL 索引是从零开始的),因此会出现段错误。
评论 /*assume this contains a bunch of values*/
没有帮助,因为您的代码没有显示 in
包含任何内容。
使用 vector(size_t n, const value_type& val)
构造函数重载为向量提供初始值以修复此错误:
using namespace std;
...
vector<int> in(51, 0); // initializes the vector with 51 values of zero
vector<int> out( in.size() ); // 51
...
assert( out[i] == int[i] + 1 );
我试图理解函子。我从 functors and their uses.
借用并修改了以下程序#include <iostream>
#include <vector>
#include <assert.h>
#include <algorithm>
/*
* A functor is pretty much just a class which defines the operator().
* That lets you create objects which "look like" a function
**/
struct add_x
{
add_x(int y) : x(y)
{
}
int operator()(int y) const {
return x + y;
}
private:
int x;
};
int main()
{
/* create an instance of the functor class*/
add_x add42(42);
/* and "call" it */
int i = add42(8);
/*and it added 42 to its argument*/
assert(i == 50);
/*assume this contains a bunch of values*/
std::vector<int> in;
std::vector<int> out(in.size());
/*
* Pass a functor to std::transform, which calls the functor on every element
* in the input sequence, and stores the result to the output sequence
*/
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
/*for all i*/
assert(out[i] == (in[i] + 1));
return 0;
}
我在 main() 的第二个断言语句中遇到分段错误。 (assert(out[i] == (in[i] + 1));
)我似乎不明白为什么?
in.size()
将 return 0
因为您还没有添加任何内容。这意味着 out
被初始化为空向量。
out[i]
将尝试访问不存在的向量的第 51 个元素(因为 STL 索引是从零开始的),因此会出现段错误。
评论 /*assume this contains a bunch of values*/
没有帮助,因为您的代码没有显示 in
包含任何内容。
使用 vector(size_t n, const value_type& val)
构造函数重载为向量提供初始值以修复此错误:
using namespace std;
...
vector<int> in(51, 0); // initializes the vector with 51 values of zero
vector<int> out( in.size() ); // 51
...
assert( out[i] == int[i] + 1 );