c++ - 无法访问成对 vector 中的值

标签 c++ vector std-pair

我有一个成对的 vector 作为对象内部的一个字段。所述对象有一个方法,我需要在其中访问 vector 中成对的值。我正在使用迭代器指向我希望访问的 vector 中的位置。以下是包含 vector 的代码片段:

在头文件中:

vector<pair<double, double> > points;
vector<pair<double, double> >::iterator headingTo;

在构造函数中:

 points.push_back(make_pair(1700.00, 3300.00));//Plus 20 or so other values
 headingTo = points.begin();

在方法中:

double x = headingTo->first - positionX;
double y = headingTo->second - positionY;

但是,当我运行这段代码时,y 并没有被创建。当我使用断点查看变量时,它根本没有显示在 Visual Studio 中。但是,如果我交换行,y 是可访问的而 x 不是。有什么想法吗?

编辑: 我发现了以下作品:

double headingToX = headingTo->first; 
headingToX -= positionX;
double headingToY = headingTo->second;
headingToY-= positionY;

最佳答案

检查您是否在调试程序的优化构建 - 在这种情况下,如果编译器可以确定不需要它们来生成程序所需的输出,则编译器可以随意删除变量。

但是,即使您使用的是未优化的构建,如果您真的根本不使用该变量,也会发生这种行为。在 this bug report on the Express version of VC++ 2010 ,您将看到 Microsoft 代表发表的以下评论(强调已添加):

Is this issue only occuring on variable that you have not used in any way other than assigning a value? The presence of the variable in the .pdb via inspection with a hex-editor, or seeing a corresponding "mov" instruction in the dissassembly does not guarantee that the compiler did not do some level of optimzation that prevents the debugger from inspecting the variable (the compiler always does small optimizations even in a debug build). The debugger can only guarantee access to a variable will be provided by the compiler if the variable is used in the application for another purpose other than being assigned a value.

If you have a repro where the variable is being used (other than being assigned a value) and you cannot inspect it in the debugger please let us know. Otherwise, this is an artifact of compiler optimizations.

从您发布的代码中不清楚您以后是否使用了 y 的值。

关于c++ - 无法访问成对 vector 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215948/

相关文章:

c++ - int 测试(无符号整数 i = -1);为什么编译器不生成警告?

c++ - std::vector::push_back 无法将数据添加到我的 vector

python - 在 python 中索引向量列表

c++ - 使 std::pair 具有固定类型的宏

c++ - 如何打印出 C++ 映射值?

c++ - OpenCV WarpPerspective 问题

c++ - 为什么 Sortable 概念需要完全有序的值类型,而 std::sort 只需要 "less than"可比较?

c++ - 如何获取远程(即不在我的进程内)线程的堆栈跟踪?

c++ - 如何修改 const 的私有(private)成员?

C++在成对 vector 中存储字符串拷贝