0

我在尝试使用 cout 从打印切换到命令行以使用 stringstream 和 streamstring.str() 将其变为字符串时遇到了这个问题。我的代码如下:

string Similarity::maxJaccard(){
    double currentJaccardValue(0.0);
    double maxJaccardValue(0.0);
    int index1(0);
    int index2(0);
    double jaccardNumerator(0.0);
    double jaccardDenominator(0.0);
    stringstream ss;

    vector<int> compareToVector;
    vector<int> compareAgainstVector;

    for(unsigned int i = 0; i < containingVector.size(); i++){
            compareToVector = containingVector.at(i);
            index1 = i;
            jaccardDenominator = compareToVector.size();
            for(unsigned int j = 0; j < containingVector.size(); j++){
                    jaccardNumerator = 0.0;
                    if(i != j){
                            compareAgainstVector = containingVector.at(j);
                            index2 = j;
                            for(unsigned int k = 0; k < compareToVector.size(); k++){
                                    if(compareToVector.at(k) == compareAgainstVector.at(k)){
                                            jaccardNumerator = jaccardNumerator + 1.0;
                                    }
                            }
                            currentJaccardValue = jaccardNumerator/jaccardDenominator;
                            if(currentJaccardValue >= maxJaccardValue){
                                    maxJaccardValue = currentJaccardValue;
                                    if(index1 < 10){
                                            ss << "New Maximum at: " << index1 << "  " << index2 << " " << printVector(compareToVector) << " " << printVector(compareAgainstVector) << " " << currentJaccardValue << "\n";

                                    }else if(index2 < 10){
                                            ss << "New Maximum at: " << index1 << " " << index2 << "  " << printVector(compareToVector) << " " << printVector(compareAgainstVector) << " " << currentJaccardValue << "\n";

                                    }else{
                                            ss << "New Maximum at: " << index1 << " " << index2 << " " << printVector(compareToVector) << " " << printVector(compareAgainstVector) << " " << currentJaccardValue << "\n";
                                    }
                            }
                    }else{
                    }
            }
    }
    string s = ss.str();
    return s;
 }

printVector 是一个简单的 for 循环,遍历每个向量中的项目并将它们作为字符串返回。返回一个字符串。

 string Similarity::printVector(vector<int> vector){
    ostringstream ss;
    string s = "( ";
    for(unsigned int i = 0; i < vector.size(); i++){
            ss << (vector.at(i));
            ss << " ";
    } s+= ss.str();
    s+= ")";
    return s;
 }

当我编译并运行时,我得到一个

 Segmentation fault (core dumped)

当代码简单地使用 cout 时,它运行得非常好。我不太确定为什么使用 cout 的流字符串会导致这种情况。

任何和所有的帮助表示赞赏,在此先感谢。

*编辑:为清楚起见进行了编辑。

4

0 回答 0