Swtiching places in a vector

Im having problem switching two string values in a vector. Im suspecting that the vector i insert isnt updatet by the fuction. Any tip?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector<string> replace(vector<string>, string, string);
void print(vector<string>);

int main ()
{
    vector<string> vec;
    vec.push_back("Lorem");
    vec.push_back("Ipsum");
    vec.push_back("Dolor");
    vec.push_back("Sit");
    vec.push_back("Amet");
    vec.push_back("Consectetur");
    
    print(vec);

vector<string> a;
    cout << endl;
    a= replace( vec, "Dolor", "Ipsum");
    cout << endl;
    print(a); 

    return 0;
}
template <class T>
void changePlace(T &a, T &b){
    T temp=a;
    a=b;
    b=temp;
}

vector<string> replace(vector<string> vec,string a,string b){
    bool A=false,B=false;
    string *ptr1=new string, *ptr2=new string;
    vector<string>::iterator it;
    for (it=vec.begin(); it!=vec.end(); it++) {
        if (a==*it) {
            A=true;
            *ptr1=*it;
        }
        if (b==*it) {
            B=true;
            *ptr2=*it;
        }
    }                                   
    if (B==true && A==true) {
        changePlace(*ptr1,*ptr2);
    }
    return vec; 
}
void print(vector<string> vec){
    vector<string>::iterator it;
    for (it=vec.begin(); it!=vec.end(); it++) {
        cout << *it << endl;
    }
}


As u see, the vector isnt upgraded:

Lorem
Ipsum
Dolor
Sit
Amet
Consectetur


Lorem
Ipsum
Dolor
Sit
Amet
Consectetur


Appreciate the help :) !
1
2
3
4
5
   string *ptr1=new string, *ptr2=new string;

...

        changePlace(*ptr1,*ptr2);



It's not clear from the function and parameter names what exactly you intended to do here, but it is almost certainly not what you're doing.

To begin, you should not be newing these strings. You have a memory leak here since there is no possibility of freeing the memory you allocated after exiting the function.

Secondly, there are no changes made to vec. What you actually do is just swap *ptr1 with *ptr2 and discard both of those values when you leave replace.

What you you should do:

Find the position of a in the vec, if it exists.
Find the position of b in the vec, if it exists.
Swap the elements at those respective positions, if both exist.

You don't need pointers for any of that.
Thanks for the help !
Topic archived. No new replies allowed.