473,785 Members | 2,843 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Specialising for iterators over contiguous memory (e.g. vector, string)

Dear All,

For some reason I had got it into my head that std::vector<T>: :iterator
and std::basic_stri ng<T>::iterator were certain to be T*. I now see
that this isn't true.

So here's why this matters to me. I have a function that is templated
on an iterator type:

template <typename Iter>
void func(Iter i) { ...... }

A common case is Iter = std::some-container<char> ::iterator. For those
containers where the elements are certain to be stored contiguously in
memory (i.e. string and vector, right?), I want to provide an optimised
specialisation: if the elements have suitable alignment, I'll cast to
int* and process them 4 or 8 at a time, rather than one at a time.
(I've already established that this is worthwhile; it's similar to
specialising std::copy to invoke memcpy().)

So, in my mistaken belief that std::vector/basic_string<ch ar>::iterator
was char*, I wrote this:

template <>
void func(char* i) <char*{ ...... }

which of course didn't work.

So presumably I could specifically detect basic_string and vector, and
invoke the char* specialisation on the address of the element:

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_str ing<char>::iter ator{
func<char*>(&(* i));
}

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_str ing<char>::iter ator{
func<char*>(&(* i));
}

Question: does that work?

But I'd really like to be able to detect any container, including
user-defined ones, where the elements are stored contiguously in memory.
Is there some way to enable the specialisation in these cases?

Many thanks for any suggestions.

Phil.

Feb 20 '08 #1
5 1792
Phil Endecott wrote:
Dear All,

For some reason I had got it into my head that
std::vector<T>: :iterator and std::basic_stri ng<T>::iterator were
certain to be T*. I now see that this isn't true.

So here's why this matters to me. I have a function that is templated
on an iterator type:

template <typename Iter>
void func(Iter i) { ...... }

A common case is Iter = std::some-container<char> ::iterator. For
those containers where the elements are certain to be stored
contiguously in memory (i.e. string and vector, right?), I want to
provide an optimised specialisation: if the elements have suitable
alignment, I'll cast to int* and process them 4 or 8 at a time,
rather than one at a time. (I've already established that this is
worthwhile; it's similar to specialising std::copy to invoke
memcpy().)
So, in my mistaken belief that
std::vector/basic_string<ch ar>::iterator was char*, I wrote this:

template <>
void func(char* i) <char*{ ...... }
Ahem... Did you mean

template<>
void func<char*>(cha r* i) { ....... }

Because the way you wrote it is a syntax error.

which of course didn't work.
In what way didn't it work?
So presumably I could specifically detect basic_string and vector, and
invoke the char* specialisation on the address of the element:

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_str ing<char>::iter ator{
Again, what is the template argument list doing after the function
argument list? It must follow the name.
func<char*>(&(* i));
}

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_str ing<char>::iter ator{
Same here. BTW, 'std::string' is the synonym for 'std::basic_str ing<char>'.
func<char*>(&(* i));
}

Question: does that work?
No, those are syntax errors.
>
But I'd really like to be able to detect any container, including
user-defined ones, where the elements are stored contiguously in
memory. Is there some way to enable the specialisation in these
cases?
Many thanks for any suggestions.
Please post real code, and post what errors do you get.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Feb 20 '08 #2
Victor Bazarov wrote:
Phil Endecott wrote:
>Dear All,

For some reason I had got it into my head that
std::vector<T> ::iterator and std::basic_stri ng<T>::iterator were
certain to be T*. I now see that this isn't true.

So here's why this matters to me. I have a function that is templated
on an iterator type:

template <typename Iter>
void func(Iter i) { ...... }

A common case is Iter = std::some-container<char> ::iterator. For
those containers where the elements are certain to be stored
contiguously in memory (i.e. string and vector, right?), I want to
provide an optimised specialisation: if the elements have suitable
alignment, I'll cast to int* and process them 4 or 8 at a time,
rather than one at a time. (I've already established that this is
worthwhile; it's similar to specialising std::copy to invoke
memcpy().)
So, in my mistaken belief that
std::vector/basic_string<ch ar>::iterator was char*, I wrote this:

template <>
void func(char* i) <char*{ ...... }

Ahem... Did you mean

template<>
void func<char*>(cha r* i) { ....... }

Because the way you wrote it is a syntax error.
Yes, sorry :-(
>which of course didn't work.

In what way didn't it work?
The specialisation was not used, and the default implementation of the
function was used.
>So presumably I could specifically detect basic_string and vector, and
invoke the char* specialisation on the address of the element:

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_st ring<char>::ite rator{

Again, what is the template argument list doing after the function
argument list? It must follow the name.
> func<char*>(&(* i));
}

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_st ring<char>::ite rator{

Same here. BTW, 'std::string' is the synonym for 'std::basic_str ing<char>'.
> func<char*>(&(* i));
}

Question: does that work?

No, those are syntax errors.
I'll try again:

template <>
void func<std::basic _string<char>:: iterator>
(std::basic_str ing<char>::iter ator i) {
func<char*>(&(* i));
}

template <>
void func<std::basic _string<char>:: iterator>
(std::basic_str ing<char>::iter ator i) {
func<char*>(&(* i));
}
Feb 20 '08 #3
Phil Endecott wrote:
Victor Bazarov wrote:
>Phil Endecott wrote:
>>Dear All,

For some reason I had got it into my head that
std::vector<T >::iterator and std::basic_stri ng<T>::iterator were
certain to be T*. I now see that this isn't true.

So here's why this matters to me. I have a function that is
templated on an iterator type:

template <typename Iter>
void func(Iter i) { ...... }

A common case is Iter = std::some-container<char> ::iterator. For
those containers where the elements are certain to be stored
contiguousl y in memory (i.e. string and vector, right?), I want to
provide an optimised specialisation: if the elements have suitable
alignment, I'll cast to int* and process them 4 or 8 at a time,
rather than one at a time. (I've already established that this is
worthwhile; it's similar to specialising std::copy to invoke
memcpy().)
So, in my mistaken belief that
std::vector/basic_string<ch ar>::iterator was char*, I wrote this:

template <>
void func(char* i) <char*{ ...... }

Ahem... Did you mean

template<>
void func<char*>(cha r* i) { ....... }

Because the way you wrote it is a syntax error.

Yes, sorry :-(
>>which of course didn't work.

In what way didn't it work?

The specialisation was not used, and the default implementation of the
function was used.
>>So presumably I could specifically detect basic_string and vector,
and invoke the char* specialisation on the address of the element:

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_s tring<char>::it erator{

Again, what is the template argument list doing after the function
argument list? It must follow the name.
>> func<char*>(&(* i));
}

template <>
void func(std::basic _string<char>:: iterator i)
<std::basic_s tring<char>::it erator{

Same here. BTW, 'std::string' is the synonym for
'std::basic_st ring<char>'.
>> func<char*>(&(* i));
}

Question: does that work?

No, those are syntax errors.

I'll try again:

template <>
void func<std::basic _string<char>:: iterator>
(std::basic_str ing<char>::iter ator i) {
func<char*>(&(* i));
}

template <>
void func<std::basic _string<char>:: iterator>
(std::basic_str ing<char>::iter ator i) {
func<char*>(&(* i));
}
Phil,

With all due respect to your effort so far, it's not enough for me
to verify that whatever you are trying to get to work does not work
and why. Please post the _complete_ _compileable_ code. We really
do not care for your proprietary stuff, but you have to post the
minimal set that anyone here can copy from your message and paste
into their IDE or the text editor and run the complier over it to
see what errors we get, and then compare them with your reported
errors. And then try to tweak your code to make it compile and
behave the way you need it to behave.

Best of luck!

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Feb 20 '08 #4
Victor Bazarov wrote:
With all due respect to your effort so far, it's not enough for me
to verify that whatever you are trying to get to work does not work
and why. Please post the _complete_ _compileable_ code.
Victor, don't worry about the syntax errors and so on. I can fix those.
The important bit is this question, which does not depend on any of
the code that I posted (and which got lost in the quoting):

"I'd really like to be able to detect any container, including
user-defined ones, where the elements are stored contiguously in memory.
Is there some way to enable the specialisation in these cases?"

Phil.
Feb 20 '08 #5
On Feb 20, 11:03*pm, red floyd <no.s...@here.d udewrote:
red floyd wrote:

Damn. *I had it written out, copied, pasted, and everything, and still
missed one element.
#include <iterator>
template<typena me ForwardIterator >
bool is_continguous( ForwardIterator first, ForwardIterator last)
{
* * bool is_contiguous = false;
* * if (first != last)
* * {
* * * * is_contiguous = true;
* * * * typename std::iterator_t raits<ForwardIt erator>::pointe r p =
&*first;
* * * * while (is_contiguous && first != last)
* * * * {
* * * * * * if (&*first != ++p)

* * * * * * * * is_contiguous = false;
* * * * * * * else
* * * * * * * * *++first.
* * * * }
* * }
* * return is_contiguous;
}
Shouldn't "first" and "p" move at the same rate meaning they should
move ahead together and then compared for pointer equality? Currently,
p is always ahead of first in the comparison for != in the if-block
within while and hence the != will always return "true" resulting in
the function to return false.

Also, this would tell if the container has contiguous blocks allocated
at runtime or not for that particular object, which could
theoretically be possible for even a non-contiguous container but
should work on that container object as it is just that instance's
contiguity that is important. It cannot be used as a generic test for
a type, though. Right?
Feb 21 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1233
by: panbru | last post by:
I'm doing some native code stuff and want to pass continguos memory blocks of data back and forth between Python and C, with the memory blocks modifiable in both realms. What is a good way to do that? As I understand it, "buffer interface" objects (e.g. strings or arrays) won't work because memory is not guaranteed to be continguous. Tim
2
5247
by: Gary Kuehn | last post by:
Is Reserve guaranteed to allocate contiguous memory? How safe is the following: vector<char> vbuff; int sz = numeric_limits<short int>::max();
5
4804
by: Alfonso Morra | last post by:
Hi, I am writing a messaging library which will allow me to send a generic message structure with custom "payloads". In many cases, a message must store a non-linear data structure (i.e. "payload") using pointers. Examples of these are binary trees, hash tables etc. Thus, the message itself contains only a pointer to the actual data. When the message is sent to the same processor, these pointers point to the original locations, which...
1
2418
by: richardconnor | last post by:
Hi, Is it possible to get use of a block of contiguous memory using JavaScript? - I'd like to use it for a project but it's efficiency-critical and I want access to a memory-addressable block. If I use a big array will an implementation create a contiguous block or just build an associative lookup table? I have been told that in a web page people use the Flash plugin if it's available for this purpose - is this really true? In which case I...
2
1975
by: Sheldon | last post by:
Hi, Can someone tell me how to remove the conflicts here ? #include <stdlib> static char*** Memory2DStr(int R, int C); static void MemoryFreeStr(int C, char*** array); void main() { unsigned char ***arr_scenes=NULL;
3
2246
by: n.torrey.pines | last post by:
I'd like to be able to view two contiguous elements of a vector as a pair. Assuming I'm not accessing the last element, of course, and the element type is not bool, when is it safe to do so, from the language definition point of view? const pr& p = *(const pr*)(&v); // pr - either std::pair or hand-defined pair of elements
5
6233
by: Azaz ul haq | last post by:
Hello! What is meant by contiguous memory allocation in C++?
1
1845
by: efittery | last post by:
I need to modify the following code to handle a vector of pairs of floats. I was just thinking of casting my vector of floats into being a vector of pairs of floats. Alternately, I have looked into using the instream iterator to initialize the vector of pairs of floats. Any thoughts would be appreciated. given the test.txt file which contains:
3
3105
by: chachi | last post by:
Hi, I want to know how to instantiate a data structure which has n bytes (given by me) and is internally stored in a contiguous fashion. I know list is not implemented like this, so I am in a fix. There seems to be a buffer object available, but haven't seen it being used anywhere. Does anyone know how to use Buffer? Say I want to write some data onto the buffer and then write the contents of the entire buffer to a file (without making...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8974
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.