how two vector to join together?

In this program class Sensor get two value as sn & temp,each Sensor is a Network and two Network join together is a Region,when I join two Network I get std::out_of_range, what am I missing??

Network.cpp:
1
2
3
4
5
6
7
8
void Network::join(Network other_network) { ‫‪//add all of sensors in other network to this network
    int i,j=0;
    sensors.push_back(other_network.sensors[j]);
    int allNet=(int)sensors.size();
    for (i = allNet ; j < (int)sensors.size(); i++, j++) {
    allNet++;
        sensors.at(i) = other_network.sensors.at(j);
    }

Region.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Region::join_networks(int sn1, int sn2) {
    int indexNetwork2,indexNetwork1=0; //Number of network to be join
    int allNet = (int) r_networks.size() + indexNetwork1;
    for (int i = 0; i < allNet; i++) {
        if (r_networks.at(i).contains(sn1)) {//for check each network has sn of sensor
            indexNetwork1 = i;
        } else if (r_networks.at(i).contains(sn2)) {
            indexNetwork2 = i;
        }
    }
    r_networks[indexNetwork1].join(r_networks[indexNetwork2]);
    indexNetwork1++;
    for (int i = indexNetwork2; i < (int)r_networks.size() - 1; i++) {
        r_networks.at(i) = r_networks.at(i + 1);
    }
    indexNetwork2--;
    //allNet--;
}
Last edited on
When adding to a vector, you should be using something like push_back(), not assigning to at(). at() assumes that element already exists and tries to get it, which will fail immediately in your case as you try to access past the end of sensors.

However, I would just use sensors.insert(sensors.end(), other_network.sensors.begin(), other_network.sensors.end()); instead of that loop.
I think you say true thank you....
Topic archived. No new replies allowed.