c++ - 关于 vector 值

标签 c++ vector stl

这是下面的代码片段。 程序的输入是

dimension d[] = {{4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}};
PVecDim vecdim(new VecDim());
    for (int i=0;i<sizeof(d)/sizeof(d[0]); ++i) {
        vecdim->push_back(&d[i]);
    }
getModList(vecdim);

程序:

class dimension;
typedef shared_ptr<vector<dimension*> > PVecDim;
typedef vector<dimension*> VecDim;
typedef vector<dimension*>::iterator VecDimIter;

struct dimension {
    int height, width, length;
    dimension(int h, int w, int l) : height(h), width(w), length(l) {

    }
};

PVecDim getModList(PVecDim inList) {
        PVecDim modList(new VecDim());
        VecDimIter it;

        for(it = inList->begin(); it!=inList->end(); ++it) {
            dimension rot1((*it)->length, (*it)->width, (*it)->height);
            dimension rot2((*it)->width, (*it)->height, (*it)->length);

            cout<<"rot1 "<<rot1.height<<" "<<rot1.length<<" "<<rot1.width<<endl;
            cout<<"rot2 "<<rot2.height<<" "<<rot2.length<<" "<<rot2.width<<endl;

            modList->push_back(*it);
            modList->push_back(&rot1);
            modList->push_back(&rot2);
            for(int i=0;i < 3;++i) {
                cout<<(*modList)[i]->height<<" "<<(*modList)[i]->length<<" "<<(*modList)[i]->width<<" "<<endl;
            }
        }
            return modList;
}

我看到的是值 rot1 和 rot2 实际上覆盖了以前的值。 例如,对于顶部定义的输入值,cout 语句打印如下。谁能告诉我为什么这些值会被覆盖?

rot1 7 4 6
rot2 6 7 4
4 7 6 
7 4 6 
6 7 4 
rot1 3 1 2
rot2 2 3 1
4 7 6 
3 1 2 
2 3 1 

最佳答案

当你做这种事情时,你正在存储指向局部变量的指针:

modList->push_back(&rot1);

这些在每个循环周期都会失效。如果一开始就不存储指针,您可以省去很多麻烦。

关于c++ - 关于 vector 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21131050/

相关文章:

c++ - Winsock编程

c++ - Qt 对话框窗口在同一窗口中打开

vector - 如何重写 Vec.append "in favor of"扩展?

c++ - 在模板类中使用 vector 迭代器

c++ - C++ 的 STL 的 unary_function(在 gcc 4.7.x 中实现)可以有虚函数吗?

c++ - 如何在 C++ 中使用 Bluez5 DBUS API 来配对和连接新设备?

c++ - 我可以在 native 代码中包含托管代码吗?

c++ - 模板函数和 vector 访问

c++ - vector<Point> myArr 的深拷贝

C++ std::set::erase 与 std::remove_if