访问指针到结构中的向量

Accessing pointer to a vector in a struct

本文关键字:向量 结构 指针 访问      更新时间:2023-10-16

我如何访问指针对向量构成中的值的值?我有以下代码:

#include <iostream>  
#include <vector>
using namespace std;
struct item {
    int value;
    vector<bool> pb;
    vector<bool> *path = &pb;
};
int main(int argc, char* argv[]) {
    vector<item> dp(10);
    for (int n = 0; n < 10; n++)
        dp[n].pb = vector<bool>(10);
    if (dp[1].path[2] == true)
        cout << "true";
    else cout << "false";
}

导致以下汇编错误:

Error   C2678   binary '==': no operator found which takes a left-hand operand of type 'std::vector<bool,std::allocator<_Ty>>' (or there is no acceptable conversion)

如何访问存储在DP [1] .path [2]?

的值

路径是指向向量的指针。您必须执行以下操作以访问指向

的向量中的值
if ((*(dp[1].path))[2] == true)

if (dp[1].path->operator[](2) == true)

此外,您可以使用

at函数

检查n是否在向量

中的有效元素的范围内

代码示例

if (dp[1].path->at(2) == true)