访问类成员向量最后一项的正确方法



我从main((函数中到达了类向量的最后一个元素。但我不确定这是否是正确的方法。这是代码部分:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class myClass
{
public:
std::vector <wstring> Vec;
std::vector <wstring> Vec2;
std::vector <wstring> Vec3;
// ...
std::vector <wstring> Vec35;
myClass();
};
myClass::myClass() : Vec{ L"Init" }, Vec2{ L"Init" }, Vec3{ L"Init" }, Vec35{ L"Init" } {}

void func(std::vector<wstring>& v)
{
v.push_back(L"The Last Element");
}
int main()
{
myClass mC;
func(mC.Vec);
wstring last = *(((std::vector <wstring>&) mC.Vec).rbegin());   // Is it the correct way to do this?
std::wcout << L"Last element reached from inside of main() function is : " << last << std::endl;
return 0;
}

输出为:

Last element reached from inside of main() function is : The Last Element

使用rbegin确实是一种方式。然而,演员阵容是不必要的。

但更直接的方法是使用back.与rbegin提供必须取消引用的迭代器不同,back为您提供对最后一项的引用。

wstring last = mC.Vec.back();

无论哪种方式,您都应该首先检查向量是否empty

是的。虽然这是一种描述性的说法。

wstring last = *mC.Vec.rbegin(); 

应该足够了。无需显式强制转换。

相关内容

最新更新