473,790 Members | 3,246 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

accessing contiguous std::vector elements as a pair

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[i]);

// pr - either std::pair or hand-defined pair of elements
// v - vector instance
// i + 1 < v.size()
Dec 20 '07 #1
3 2246
On Dec 20, 6:45 pm, n.torrey.pi...@ gmail.com wrote:
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[i]);

// pr - either std::pair or hand-defined pair of elements
// v - vector instance
// i + 1 < v.size()
When is it safe to do so? whenever you take the appropriate
precautions.
In this case, std::vectors have an at(...) member function that throws
an out_of_range exception should someone accidentally attempt to
access something out of bounds. There you go - problem solved.

Using pointers for that has no safety and usually demands considerably
more work (ie: maintenance).

In the following, i'm not too worried about getting main's for-loop
wrong, it'll throw if i do. Try it.

#include <iostream>
#include <vector>
#include <stdexcept>

template< typename T >
class Container
{
std::vector< T m_v;
public:
// default ctor
Container() : m_v() { }
Container(const size_t sz, const T& t) : m_v(sz, t) { }
// member functions
void push_back(const T& t) { m_v.push_back(t ); }
void showpair(const size_t index) const
{
std::cout << "m_v[" << index << "] ";
std::cout << m_v.at(index);
std::cout << "\tm_v[" << index + 1 << "] ";
std::cout << m_v.at(index + 1);
std::cout << std::endl;
}
size_t size() const { return m_v.size(); }
};

int main()
{
try
{
Container< int container(5, 99);
container.push_ back(77);
// use i < container.size( ) to throw an exception
for(size_t i = 0; i < container.size( ) - 1; ++i)
{
container.showp air(i);
}
}
catch(const std::exception& e)
{
std::cout << "\nError: ";
std::cout << e.what() << std::endl;
}
}

/*
m_v[0] 99 m_v[1] 99
m_v[1] 99 m_v[2] 99
m_v[2] 99 m_v[3] 99
m_v[3] 99 m_v[4] 99
m_v[4] 99 m_v[5] 77
*/


Dec 21 '07 #2
On Dec 20, 5:22 pm, Salt_Peter <pj_h...@yahoo. comwrote:
On Dec 20, 6:45 pm, n.torrey.pi...@ gmail.com wrote:
I'd like to be able to view two contiguous elements of a vector as a
pair.
void showpair(const size_t index) const
{
std::cout << "m_v[" << index << "] ";
std::cout << m_v.at(index);
std::cout << "\tm_v[" << index + 1 << "] ";
std::cout << m_v.at(index + 1);
std::cout << std::endl;
}


:-)

This is a joke, right?

If not, I didn't mean "view" in the common sense, and "at()" doesn't
add any safety if the index is already guaranteed to be in [0 ..
size()-2]
Dec 21 '07 #3
On Dec 21, 12:45 am, n.torrey.pi...@ gmail.com wrote:
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[i]);
// pr - either std::pair or hand-defined pair of elements
// v - vector instance
// i + 1 < v.size()
Anytime your implementation gives you a special guarantee that
this will work. It's undefined behavior according to the
standard (even though it's likely to work most of the time in a
lot of implementations ).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Dec 21 '07 #4

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

Similar topics

10
7079
by: Stefan Höhne | last post by:
Hi, as I recon, std::vector::clear()'s semantics changed from MS VC++ 6.0 to MS' DOT.NET - compiler. In the 6.0 version the capacity() of the vector did not change with the call to clear(), in DOT.NET the capacity() is reduced to 0.
4
12260
by: enzo | last post by:
hi all, i don't understand what's wrong: 1) std::vector<double> p(10); doesn't compile:
18
2881
by: Janina Kramer | last post by:
hi ng, i'm working on a multiplayer game for a variable number of players and on the client side, i'm using a std::vector<CPlayer> to store informatik about the players. CPlayer is a class that contains another std::vector<CPosition>. Because one of the players is the client itself (and the size of the vector<CPlayer> doesn't change during a game), i thought i could store a std::vector<CPlayer>::iterator "localplayer" that points to the...
11
8882
by: Steve | last post by:
Hi, I'm using a std::vector to store a list of user defined objects. The vector may have well over 1000 elements, and I'm suffering a performance hit. If I use push_back I get a much worse perfomance than if I first define the vector of a given size, then write to the elements with myvec = However, I'm currently thinking that it isn't feasible to obtain the vector size, so really need to resize the vector dynamically as I go. Is...
6
8029
by: Jason Heyes | last post by:
What is a good way of removing elements from std::vector so that the elements removed satisfy a predicate and end up stored in another std::vector. It seems as though the algorithm std::remove_if only achieves half the job. Here is how I would use std::remove_if to remove elements from std::vector based on predicate: v.erase(std::remove_if(v.begin(), v.end(), pred), v.end()); After that line is executed I cannot get back the elements...
20
17838
by: Anonymous | last post by:
Is there a non-brute force method of doing this? transform() looked likely but had no predefined function object. std::vector<double> src; std::vector<int> dest; std::vector<double>::size_type size = src.size(); dest.reserve(size); for (std::vector<int>::size_type i = 0;
8
5115
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value types or std::vector<int>. So where I would use an int* and reallocate it from time to time in C, and randomly access it via , then I figure to copy the capacity and reserve methods, because I just need a growable array. I get to considering...
7
3015
by: Dilip | last post by:
If you reserve a certain amount of memory for a std::vector, what happens when a reallocation is necessary because I overshot the limit? I mean, say I reserve for 500 elements, the insertion of 501st element is going to cause some more allocation -- for arguments sake if the vector re-grows to accomodate 1000 elements, I play around with it and completely erase everything in it after I am done. Now how much does the vector hold? Do I...
4
2321
by: mathieu | last post by:
Hello, I am looking at the API of std::vector but I cannot find a way to specify explicitely the size of my std::vector. I would like to avoid vector::resize since it first initializes the elements of the vector. Thank you ! Mathieu Code:
0
9512
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,...
0
10419
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10201
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9987
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9023
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
7531
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
6770
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4100
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
3
2910
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.