c++ - vector push_back导致未处理的异常

标签 c++ vector push-back

一切正常,直到编译器尝试执行push_back操作。 在 if 条件下返回正确的值。
我已将项目声明为:

vector<int> items; // inside the header file.

//.cpp 文件内

void MsPs::findnSort()
{
    for(int i = 1; i<50 ; i++)
    {

        string temp = static_cast<ostringstream*>( &(ostringstream() << i) )->str();    // TO convert int i to a string temp
        if(findSupport(temp) >= MIS[i])
        {
            items.push_back(i);
        }

    }

}

弹出以下错误:

Unhandled exception at 0x5052ad4a (msvcp100d.dll) in PrefixScan.exe: 0xC0000005: Access violation reading location 0x3d4cccd1.

PS:我还有一个使用 Push_back 操作的函数,并且工作正常。

谁能帮我解决这个问题吗?

即使这样也会产生相同的错误:

void MsPs::findnSort()
{
    for(int i = 1; i<50 ; i++)
    {

        items.push_back(i);
    }


}

最佳答案

我认为问题在于静态转换返回时 ostringstream 被破坏。因此,当调用 str() 时,您的指针悬空。试试这个:

void MsPs::findnSort()
{
    for(int i = 1; i<50 ; i++)
    {
        ostringstream blah;
        string temp = (blah << i).str();

        if(findSupport(temp) >= MIS[i])
        {
            items.push_back(i);
        }

    }

}

关于c++ - vector push_back导致未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14905540/

相关文章:

c++ - 由另一个数组中的值组成的数组

c++ - 如何将元素移动到 vector 的末尾?

c++ - std::vector push_back() 语义

matrix - 将 2 个 Int 列表一起添加 F#

c++ - 为什么 "std::vector<bool>"的大小是 16 Byte?

c++ - std::vector::push_back() 不能在 MSVC 上为具有已删除移动构造函数的对象编译

c++ - 从 C++ 到 Swift 的 CoreAudio 东西

c++ - 在 GLM 旋转对象不再居中之后

c++ - 无法在循环 C++ 中打开文件

Python:来自数组的随机矩阵