我試圖通過我的向量循環,並獲取存儲在向量中的項目的地址。它適用於其他類型的迭代器(見下文),但是當我嘗試這樣做的for(auto it :my_vec)
它拋出錯誤說error: no match for 'operator*' (operand type is 'my_class')
如何獲取基於循環的範圍內的對象的地址?
#include <iostream>
#include <vector>
class my_class{
int x;
public:
my_class(int x_):x(x_){}
};
std::vector<my_class> my_vec;
void fill_vec(size_t size){
for(int i = 0; i < size; i++){
my_vec.push_back(my_class(i));
}
}
int main(){
size_t size = 10;
fill_vec(size);
for(auto it :my_vec){
std::cout << &it << std::endl;
std::cout << &(*it) << std::endl;
}
std::cout << "-----------" << std::endl;
for(auto it = my_vec.begin(); it != my_vec.end(); it++){
std::cout << &(*it) << std::endl;
}
std::cout << "-----------" << std::endl;
for(size_t i = 0; i < my_vec.size(); i++){
std::cout << &my_vec[i] << std::endl;
}
return 0;
}
基於範圍的for循環獲取值,而不是迭代器。使用'auto&it:myVec'來獲取對'myVec'中對象的引用。 – zneak
@zneak謝謝你..那麼做 – solti
@zneak爲什麼你刪除你的回答說這個? – Barmar