访问集合中的元素?

时间:2010-03-29 20:16:07

标签: c++ set

使用矢量,我可以执行以下操作:

vector<int> myvec (4,100);
int first = myvec.at(0);

我有以下一套:

set<int> myset;
myset.insert(100);
int setint = ????

如何访问我在集合中插入的元素?

5 个答案:

答案 0 :(得分:14)

set<int>::iterator iter = myset.find(100);
if (iter != myset.end())
{
    int setint = *iter;
}

答案 1 :(得分:9)

您无法通过索引访问set元素。您必须使用迭代器访问元素。

set<int> myset;
myset.insert(100);
int setint = *myset.begin();

如果您想要的元素不是第一个,那么将迭代器推进到该元素。您可以使用set<>::find()查看集合以查看元素是否存在,或者您可以遍历集合以查看哪些元素存在。

答案 2 :(得分:2)

您也可以使用此方法:

 set<int>:: iterator it;
 for( it = s.begin(); it!=s.end(); ++it){
    int ans = *it;
    cout << ans << endl;
 }

答案 3 :(得分:0)

要访问特定索引,您可以使用以下方法:

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim arrCopy As Variant, lastColT As Long
  If Target.Column = 8 Then
        If Target = "COMPLETED" Then
             Set tbl = Sheets("PMI ARCHIVE").ListObjects("Table3")
             tbl.ListRows.aDD
             nxtTblRow = tbl.ListColumns(9).Range.Rows.Count

             lastColT = Cells(Target.row, Columns.Count).End(xlToLeft).Column
             arrCopy = Range(Target.row, lastColT).Value
             tbl.Range(nxtTblRow, 1).Resize(, UBound(arrCopy, 2)).Value = arrCopy

             Application.EnableEvents = False
                Range(Target.row, lastColT).SpecialCells(xlCellTypeConstants).ClearContents
             Application.EnableEvents = True
            'If in column A:A, an empty cell will exist (because of the above code), the range will be set up to that empty cell. 
            'The next way, goes to the last cell:
            Range("A1", Range("A" & Rows.Count).End(xlUp)).Sort Key1:=Range("A1"), _
                                               Order1:=xlAscending, Header:=xlYes
    End If
  End If
End Sub

下一个函数将set迭代器返回到该位置。 通常,不使用此函数,因为其性能是线性的。但是,如果集合足够小并且需要访问某些特定索引,则可以使用它来避免编写手动迭代循环。

答案 4 :(得分:0)

如果性能不重要,还可以临时复制到 vector 中,以便使用惰性单行访问特定元素。

int setint = vector<int>(myset.begin(), myset.end()).at(0);

将 .at(0) 替换为任何索引(您确定),或替换为 .back() 以获取最后一个元素。