簡體   English   中英

訪問C ++結構的各個元素

[英]Accessing individual elements of C++ structure

這是我遇到的問題,如果我不能很好地解釋它或代碼質量不好,請不要打擾我-到目前為止,我只完成了大約2周的C ++工作。

說明:我想構建一個結構(一個結構可能不是最好的決定,但我必須從某個地方開始),該結構將包含一組點的坐標(僅將x和y表示)(將其稱為圓弧), ID(可能還有其他字段)。 每個集合(弧)可以包含各種數量的點。 我已經將集合(arc)中的每個點實現為類,然后我的arc結構在矢量中(包括其他內容)包含了該類的各種實例。

弧形結構的示例:

Struc1:

ID(int)1

xY(向量)(0; 0)(1; 1)(2; 2)

Struc2:

ID(int)2

xY(向量)(1; 1)(4; 4)

問題:我不知道如何訪問我的弧形結構中的元素:例如,如果我需要使用ID 1訪問結構中第二個點的坐標,則需要Struc1.xY[1] ,但這並沒有不能按照我的代碼(如下)所述工作。 我發現這篇文章解釋了如何在結構內部打印值,但是我將需要訪問這些元素以(有條件地)有條件地編輯這些坐標。 如何實現這一目標?

我的嘗試:(已編輯)

#include <cmath>
#include <vector>
#include <cstdlib> 
#include <stdio.h>
#include <iostream>

using namespace std;

class Point
  {
  public:
      Point();
      ~Point(){ }

      void setX (int pointX) {x = pointX; }
      void setY (int pointY) {y = pointY; }
      int getX() { return x; }
      int getY() { return y; }

  private:
      int x;
      int y;
  }; 

Point::Point()
    {
        x = 0;
    y = 0;
    }

struct arc {
  int id;
  vector<Point> xY;
};

int main(){

  arc arcStruc;
  vector<Point> pointClassVector;
  int Id;
  int X;
  int Y;
  // other fields go here

  arc *a;

  int m = 2; // Just create two arcs for now
  int k = 3; // each with three points in it
  for (int n=0; n<m; n++){    
    a = new arc;
    Id = n+1;
    arcStruc.id = Id;
    Point pt;
    for (int j=0; j<k; j++){            
      X = n-1;
      Y = n+1;      
      pt.setX(X);
      pt.setY(Y);
      arcStruc.xY.push_back(pt);

    }
  }

for (vector<Point>::iterator it = arcStruc.xY.begin(); it != arcStruc.xY.end(); ++it)
  {
    cout << arcStruc.id.at(it);
    cout << arcStruc.xY.at(it);
  }

  delete a;  
  return 0;
}

一些建議:

  • 不用理會單獨的pointClassVector ,只需使用arcStruc.xY.push_back()即可創建Point對象,並將其直接添加到arcStruc.xY中。 arcStruc.xY = pointClassVector觸發整個矢量的副本,這有點浪費CPU周期。
  • 絕對沒有必要嘗試在堆上創建Point對象,所有要做的就是增加復雜性。 只需使用Point pt; 並調用其上的set函數-盡管我個人將完全放棄set函數並直接在Point中操作數據,但不需要getter / setter方法,它們也不會為您買任何東西。 如果這是我的代碼,我將編寫點構造函數以將x和y作為參數,這樣可以節省大量不必要的代碼。 您也不需要為析構函數提供實現,編譯器生成的就可以了。

如果要遍歷向量,則可能應該使用迭代器,而不是嘗試索引到容器中。 無論哪種方式,您都可以訪問arcStruc.xY以獲取其大小,然后使用[]運算符或使用迭代器分別訪問元素,如下所示:

 for (vector<Point>::iterator it = arcStruc.xY.begin(); it != arcStruc.xY.end(), ++it)
 {
    ... do something with it here, it can be derefernced to get at the Point structure ...
 }

暫無
暫無

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

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