[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: stl-vector of pointers to elements of another vector
From: |
Guy Harrison |
Subject: |
Re: stl-vector of pointers to elements of another vector |
Date: |
Sun, 23 Jan 2005 02:00:09 GMT |
User-agent: |
KNode/0.8.1 |
Lutz Gebhardt wrote:
> Hi,
>
> I'm trying to port a self-written C++ program to an Opteron machine with
> gcc 3.3.3 (SuSE Linux) in 64-bit mode. The program compiles and runs fine
> on SGI and SUN machines with the respective native compilers. On the Linux
> machine I have difficulties with the following piece of code (original
> code boiled down into a test snippet):
>
> #include <iostream>
> #include <vector>
> #include <stdlib.h>
>
> using namespace std;
>
> int main()
> {
> std::vector<int> testlist;
> for (int i=0; i<10; i++)
> testlist.push_back(i);
>
> std::vector<int*> testselect;
> std::vector<int>::iterator test_itr = testlist.begin();
> while (test_itr != testlist.end())
> {
> cout << *test_itr << endl;
> if (*test_itr % 2 == 0)
> {
> cout << "Even number: " << *test_itr << endl;
> testselect.push_back(test_itr); // **** Problem statement
> *****
> }
> test_itr++;
> }
> }
>
> My goal is to save pointers to selected elements from one STL-vector
> (testlist) into another (testselect) for later reference. With g++ I get
> the following compiler errors:
>
> main.cpp: In function `int main()':
> main.cpp:21: error: no matching function for call to `std::vector<int*,
> std::allocator<int*> >::push_back(__gnu_cxx::__normal_iterator<int*,
> std::vector<int, std::allocator<int> > >&)'
> /usr/include/g++/bits/stl_vector.h:596: error: candidates are: void
> std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int*,
> _Alloc = std::allocator<int*>]
>
> Might this be caused by a missing implementation in the gcc-supplied STL
> or am I doing something very bad here which works just by chance on the
> other platforms?
>
> Any help is greatly appreciated!
In addition to Paul's comments, you could have declared...
std::vector<std::vector<int>::iterator> testselect;
...but, unless your actual code is working upon a "const" testselect then
you're better off using indices where vector<> is concerned. Still assuming
vector<> a couple more possibilites...
int main()
{
std::vector<int> testlist;
for (int i=0; i<10; i++)
testlist.push_back(i);
std::vector<int*> testselect;
std::vector<std::size_t> test_idx;
std::vector<int>::iterator test_itr = testlist.begin();
while (test_itr != testlist.end())
{
cout << *test_itr << endl;
if (*test_itr % 2 == 0)
{
cout << "Even number: " << *test_itr << endl;
testselect.push_back(&(*test_itr));
test_idx.push_back(test_itr - testlist.begin());
}
test_itr++;
}
int *p(&testlist[0]);
int **pp(&testselect[0]);
for (std::size_t i = 0; i < test_idx.size(); i++)
std::cout<<"i="<<i<<','
<<(void*)(&testlist[test_idx[i]])<<','
<<(void*)(&p[test_idx[i]])<<','
<<(void*)(*pp++)
<<','<<testlist[test_idx[i]]
<<'\n'
;
}