簡體   English   中英

訪問指向結構中向量的指針

[英]Accessing pointer to a vector in a struct

如何訪問結構中向量的指針值? 我有以下代碼:

#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]中的值?

path是指向向量的指針。 您必須執行以下操作才能訪問其指向的向量中的值

if ((*(dp[1].path))[2] == true)

要么

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

此外,您還可以使用at 函數

檢查n是否在向量的有效元素范圍內

代碼示例

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM