[英]Why is this iterator arithmetic not working?
我學習 C++ 是為了好玩。 我試圖理解迭代器算術並編寫了一個簡單的程序,它將向量中的第一個元素與最后一個元素相加。 接下來將第二個和倒數第二個元素相加。 該過程繼續進行,直到所有元素都以這種方式求和。
問題似乎與我的代碼的*(a.end() - 1 - it)
部分有關。 如果我刪除- it
,那么我會得到我期望的結果。 添加- it
導致錯誤提示
有構建錯誤。 您想繼續運行上次成功的構建嗎?
我從 Visual Studio 收到的錯誤如下;
E0075
*
的操作數必須是指針C2100 非法間接
我已經以不同的方式解決了這個問題,並且能夠實現我的目標。 我的問題是為什么這段代碼是錯誤的,可以稍微修改一下以正確執行嗎?
我很感激任何建議。
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
vector<int> a{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto it = a.begin(); it != a.begin() + (a.end() - a.begin()) / 2; ++it)
cout << (*it) + *(a.end() - 1 - it) << endl;
return 0;
} // END MAIN
用a.end() - 1 - it
為您提供它們之間的距離。 您不能使用*
取消引用距離,因此會出現編譯器錯誤。
表達式中需要從a.begin()
到您想要到達的元素的距離。 您可以通過將a.begin()
添加到該距離來稍微調整表達式:
cout << (*it) + *(a.end() - 1 - it + a.begin()) << endl;
// ^^^^^^^^^^^
這是一個演示。
從 C++20 開始,您可以直接處理范圍,而不是處理迭代器和操作它們,一旦習慣了它會更容易閱讀:
// just for convenience
namespace sv = std::views;
namespace sr = std::ranges;
// size of half the range
auto half = a.size() / 2;
sr::transform(a | sv::take(half), // first half
a | sv::reverse | sv::take(half), // second half reversed
std::ostream_iterator<int>(std::cout, "\n"), // print out
std::plus{}); // the sum
這是一個演示。
您應該像這樣更改代碼:
auto fix = it - a.begin();
cout << (*it) + *(a.end() - 1 - fix) << endl;
你不能像整數一樣操作迭代器,你可以簡單地添加或子整數或使用 begin() 的起點 - 因為 end() 不是向量中某個值的真實指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.