Problem with iterator arithmetic

I am having a problem with iterators for a forward_list. I am trying to erase a portion of a forward_list using erase_after which takes iterators as its arguments. I am trying to delete from the beginning of the forward_list to a specified index. I tried using pointer arithmetic, but it does not work.

1
2
3
4
5
6
7
8
9
                T* pData2 = (T*) pData;
		std::forward_list<T> list(bufferFrameCount * audioFormat.nChannels());
		std::swap_ranges(list.begin(), list.end(), source.begin());
		source.erase_after(source.begin(), source.begin() + (list.end() - list.begin()));
		typename std::forward_list<T>::iterator iter = list.begin();
		for(UINT32 i = 0; i < (list.end() - list.begin()); i++) {
			pData2[i] = (*iter);
			iter++;
		}


In particular:
source.erase_after(source.begin(), source.begin() + (list.end() - list.begin()));

How would I do something like this?
Last edited on
Only random access iterators support arithmetic operators. See http://www.cplusplus.com/reference/iterator/

There are http://www.cplusplus.com/reference/iterator/distance/ to get a number
and http://www.cplusplus.com/reference/iterator/advance/ to get iterator to begin() + n

However, the problem that you show does not seem to need either.

You create 'list' that contains N elements.
You swap N elements from start of 'list' to start of 'source'.
Now first N elements of 'source' are nonsense.
You proceed to remove those N elements from 'source'.

Why don't you simply split the 'source' so that first N elements form new 'list' and 'source' keeps the rest?
http://www.cplusplus.com/reference/forward_list/forward_list/splice_after/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// forward_list::splice_after
#include <iostream>
#include <forward_list>

int main ()
{
  std::forward_list<int> source = { 1, 2, 3, 10, 20, 30 };
  std::forward_list<int> list;

  auto it = source.begin();
  std::advance(it, 3);
  list.splice_after( list.before_begin(), source, source.before_begin(), it );

  std::cout << "source contains:";
  for (int& x: source) std::cout << " " << x;
  std::cout << std::endl;

  std::cout << "list contains:";
  for (int& x: list) std::cout << " " << x;
  std::cout << std::endl;
}

Wow, I thought about "source.splice_after" and how that wouldn't work. "list.splice_after" did not even occur to me. Thank you!
Tbh, I've never used forward_list and hence splice_after. A split felt natural operation for a linked list and browsing the documentation pointed to splice_after, whose description I had to read very carefully to figure out who is from and who is to.
Topic archived. No new replies allowed.