为什么是c++;can';t printf向量B[0]&xFF1F; #包括 #包括 #包括 使用名称空间std; int main(){ std::载体B; B[0]=0.5*log(sqrt(2)+1.0); printf(“%f”,B[0]); 返回0; } 这是一个简单的C++代码。但它不能正确打印F。它向我显示分段错误。为什么?(linux,C++11)

为什么是c++;can';t printf向量B[0]&xFF1F; #包括 #包括 #包括 使用名称空间std; int main(){ std::载体B; B[0]=0.5*log(sqrt(2)+1.0); printf(“%f”,B[0]); 返回0; } 这是一个简单的C++代码。但它不能正确打印F。它向我显示分段错误。为什么?(linux,C++11),c++,linux,vector,C++,Linux,Vector,您声明了一个空向量。因此,您可以不使用下标运算符Insetad,而使用成员函数push_back 比如说 #include<iostream> #include<vector> #include<math.h> using namespace std; int main(){ std::vector<double> B; B[0]=0.5 * log(sqrt(2) + 1.0); printf("%f",B[0]);

您声明了一个空向量。因此,您可以不使用下标运算符Insetad,而使用成员函数push_back

比如说

#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
int main(){
    std::vector<double> B;
    B[0]=0.5 * log(sqrt(2) + 1.0);
    printf("%f",B[0]);
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
std::载体B;
B.推回(0.5*log(sqrt(2)+1.0));
printf(“%f”,B[0]);
返回0;
}
另一种方法是最初用一个元素定义向量,如

#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
int main(){
    std::vector<double> B;
    B.push_back( 0.5 * log(sqrt(2) + 1.0) );
    printf("%f",B[0]);
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
std::载体B(1);
B[0]=0.5*log(sqrt(2)+1.0);
printf(“%f”,B[0]);
返回0;
}

std::vector B
创建一个空向量,然后
B[0]
尝试访问其中不存在的第一个元素分段故障通常用于访问您不可用的内存。在这种情况下,您应该做的是
将值
'0.5*log(sqrt(2)+1.0)
推回
B

您没有索引0。首先为索引0保留空间感谢您的帮助。@acraig5075
B[0]=0.5*log(sqrt(2)+1.0)--将其更改为
B.at(0)=0.5*log(sqrt(2)+1.0)你将得到一个<代码> STD::OutoFixOng/<代码>异常而不是一个分割错误,基本上解释了问题所在。相关的,因为你正在使用C++,你应该使用像“代码> CUT<代码>的STD流,而不是<代码> Prtff<代码>。不需要尝试半怀孕。一路走。
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
int main(){
    std::vector<double> B( 1 );
    B[0]=0.5 * log(sqrt(2) + 1.0);
    printf("%f",B[0]);
    return 0;
}