Bonjour à tous,

Après de nombreuses recherches infructueuses sur le sujet (mauvais mots clefs?), je pose ici ma première question.

Je cherche à réaliser la division et multiplication d'un std::vector par un double. Et je commence à devenir fou!

Voici un code restreint qui... ne fonctionne pas.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
 
#include <iostream>
#include <vector>
 
template< typename T>
void show(std::vector< T > A)
{
    for(std::size_t i = 0; i < A.size(); ++i) {
        std::cout << A[i] << std::endl;
    }
}
 
template< typename T>
std::vector<T>& operator*(const T& a, std::vector<T> B)
{
    for(std::size_t i = 0; i < B.size(); ++i) {
        B[i] = a*B[i];
    }
    return B;
}
 
 
 
int main()
{
    std::cout << "Hello world!" << std::endl;
 
    std::vector<int> A(5), B;
 
    for(std::size_t i = 0; i < A.size(); ++i) {
        A[i] = (int)i;
    }
    std::cout << " A = " << std::endl;
    show(A);
    B = A;
    A = 5 * B;
 
    std::cout << " 5*A = " << std::endl;
    show(A);
 
    std::cout << " B = " << std::endl;
    show(B);
 
 
    return 0;
}
J'obtiens le bon résultat, mais le warning me semble dangereux.

D:\vector_overload\main.cpp||In function 'std::vector<T>& operator*(const T&, std::vector<T>) [with T = int]'
D:\vector_overload\main.cpp:35|13|instantiated from here|
D:\vector_overload\main.cpp|13|warning: reference to local variable 'B' returned|
||=== Build finished: 0 errors, 1 warnings ===|
Je suis sous code::blocks avec MINGW.

J'essaie aussi de faire l'opérateur *=, mais c'est encore pire!

Merci à tous.