我从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
是。尽管这是一种描述性的方式。
只是
wstring last = *mC.Vec.rbegin();
应足够。无需显式转换。
使用rbegin
确实是一种方法。但是,强制转换是不必要的。
但是更直接的方法是使用back
。与back
为您提供必须取消引用的迭代器不同,rbegin
为您提供对最后一项的引用。
back
无论哪种方法,首先应检查向量不是wstring last = mC.Vec.back();
。